在winform中实现带Placeholder提示文本的textbox文本编辑框控件

时间:2019-10-8 作者:WilliamChan

winform中的textbox控件没有Placeholder提示文本这样的属性,使用中需要用到,因此只能通过扩展事代码来实现,这里例举两个实现的方法。

事件法

话不多说,直接上代码

    /// <summary>
    /// 控件注册
    /// </summary>
    /// <param name="txb"></param>
    /// <param name="placeholder"></param>
    void RegTextboxPlaceholder(System.Windows.Forms.TextBox txb, string placeholder="请输入")
    {
        txb.Enter += new System.EventHandler(Textbox_Enter);
        txb.Leave += new System.EventHandler(Textbox_Leave);
        txb.Tag = placeholder;
    }

    /// <summary>
    /// textbox获得焦点时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void Textbox_Enter(object sender, EventArgs e)
    {
        var txb = sender as System.Windows.Forms.TextBox;
        if (txb.Text == txb.Tag?.ToString())
        {
            txb.Text = "";
        }
        txb.ForeColor = Color.Black;
    }

    /// <summary>
    /// textbox失去焦点
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Textbox_Leave(object sender, EventArgs e)
    {
        var txb = sender as System.Windows.Forms.TextBox;
        if (txb.Text == "")
        {
            txb.Text = txb.Tag?.ToString();
            txb.ForeColor = Color.LightGray;
        }
    }

用的时候,在界面渲染前注册一个控件事件就好了:


RegTextboxPlaceholder(txb, "提示文本");

继承控件重写法

新建一个类,继承控件TextBox,代码如下:

 
using System.Drawing;
using System.Windows.Forms;

namespace WilliamChan
{
    /// <summary>
    /// 带PlaceHolder默认说明文本的textbox by WilliamChan
    /// </summary>
    public partial class TextBoxWithPlaceHolder : TextBox
    {
        public String PlaceHolder { get; set; }
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 0xF || m.Msg == 0x133)
            {
                WmPaint(ref m);
            }
        }
        private void WmPaint(ref Message m)
        {
            Graphics g = Graphics.FromHwnd(base.Handle);
            if (!String.IsNullOrEmpty(this.PlaceHolder) && string.IsNullOrEmpty(this.Text))
            {
                g.DrawString(this.PlaceHolder, this.Font, new SolidBrush(Color.LightGray), 0, 1.5f);
            }
        }
    }
}

 

用的时候,直接拉控件就OK了,设置PlaceHolder属性值,或者new个新类,代码:


var txb = new TextBoxWithPlaceHolder(){PlaceHolder = "提示文本"};

好了,知道不通过扩展事件和继承控件重写两种方法给Textbox控件加上了Placeholder提示文本的功能,希望大家能用得到。

声明:若您对本文内容有任何意见,欢迎发送邮件至:admin@zhidaobu.com,本站会尽快回应并做出相应处理。