看到很多网站上的输入框都有空值提示,即:输入框中没有内容且没有焦点时,输入框中显示的是提示文字;如果有内容或者拥有焦点,则正常显示。我觉得这东西很有意思,在某些应用中,可以减少界面排版上的麻烦,可惜WinForm中的TextBox没有此功能,于是自己做了一个,效果嘛,还算满意的:) public class TEditBox : System.Windows.Forms.TextBox { public TEditBox() : base() { } private string _Caption = "Please Input"; /**//// <summary> /// 提示内容 /// </summary> public string Caption { get { return _Caption; } set { _Caption = value; if (!DesignMode && Nothing) base.Text = value; } } private System.Drawing.Color _CaptionColor = System.Drawing.SystemColors.Control; /**//// <summary> /// 提示字体的颜色 /// </summary> public System.Drawing.Color CaptionColor { get { return _CaptionColor; } set { if (!DesignMode && !Focused && Nothing) base.ForeColor = value; _CaptionColor = value; } } private System.Drawing.Color _ForeColor = System.Drawing.SystemColors.WindowText; public new System.Drawing.Color ForeColor { get { return base.ForeColor; } set { if (!this.DesignMode) { if (Focused || !Nothing) base.ForeColor = value; _ForeColor = value; } else base.ForeColor = value; } } private bool HaveNothing = true; private bool Nothing { get { return HaveNothing || this.Text == ""; } } public new string Text { get { if (!Focused && HaveNothing) return ""; else return base.Text; } set { base.Text = value; HaveNothing = value == ""; if (Nothing && !Focused) { base.Text = _Caption; base.ForeColor = _CaptionColor; } else { if (base.ForeColor != _ForeColor) base.ForeColor = _ForeColor; } } } protected override void OnGotFocus(EventArgs e) { if (Nothing) base.Text = ""; if (base.ForeColor != _ForeColor) base.ForeColor = _ForeColor; base.OnGotFocus(e); } protected override void OnLostFocus(EventArgs e) { HaveNothing = base.Text == ""; if (Nothing) { base.Text = _Caption; base.ForeColor = _CaptionColor; } else { if (base.ForeColor != _ForeColor) base.ForeColor = _ForeColor; } base.OnLostFocus(e); } public new void Clear() { this.Text = ""; } } 属性Caption和CaptionColor是新增的,用来存储提示文字和提示文字的颜色 转载于:https://www.cnblogs.com/AndyHai/archive/2007/09/19/898436.html