场景: 对于输入框,如果用户不知道要输入什么,这个时候有个提示是最好了,下面是带提示说明的搜搜输入框,如图
C# Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; namespace EMR { public class SerachBox:TextBox { public string _HintString = "请输入住院号或姓名查询病历信息"; public SerachBox() { this.Margin = new Padding(0,0,0,0); this._SerachButton.Text = "搜索"; this._SerachButton.TextAlign = ContentAlignment.MiddleCenter; this._SerachButton.ForeColor = Color.Black; this._SerachButton.Margin = new Padding(0, 0, 0, 0); _SerachButton.BackColor = Color.Green; this.Text = _HintString; this.ForeColor = Color.Gray; _SerachButton.Size = new Size(60, this.Height); this.Controls.Add(_SerachButton); _SerachButton.Dock = DockStyle.Right; _SerachButton.Location = new Point(this.Width - 50, 0); _SerachButton.MouseHover += new EventHandler(ButtonHand); _SerachButton.MouseClick += new MouseEventHandler(ButtonClick); } private EventHandler serachHandler; public event EventHandler SerachEvent { add { serachHandler += value; } remove { serachHandler = value; } } public void ButtonClick(object sender, EventArgs e) { if(serachHandler !=null) { serachHandler.Invoke(this,null); this.Select(this.Text.Length,0);//光标移动到末尾 } } public void ButtonHand(object sender, EventArgs e) { this._SerachButton.Cursor = System.Windows.Forms.Cursors.Hand; } public void SetFontColor(bool bo) { if (bo) { this.ForeColor = Color.Gray; this._SerachButton.ForeColor = Color.Black; } else { this.ForeColor = Color.Black; this._SerachButton.ForeColor = Color.Black; } } private Label _SerachButton = new Label(); protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); //请输入住院号或姓名查询病历信息 if (this.Text == _HintString) { this.Clear(); this.SetFontColor(false); } } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); if (this.Focused && this.Text == "") { this.Text = _HintString; this.SetFontColor(true); } if (this.Text == _HintString) { this.SetFontColor(true);//显示灰色 } else { this.SetFontColor(false);//显示黑色 } } protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); e.Handled = true; if (this.Text == _HintString) { this.Text = ""; } if(e.KeyChar.ToString() == "\r") { if (serachHandler != null) { serachHandler.Invoke(this, null); this.Select(this.Text.Length, 0);//光标移动到末尾 } } this.SetFontColor(false);//显示黑色 e.Handled = false; } protected override void OnMouseHover(EventArgs e) { base.OnMouseHover(e); if (this.Focused && this.Text == _HintString) { this.Text = ""; this.SetFontColor(false);//显示黑色 } } } }
时间: 2024-10-08 05:29:37