dotNet 自定义控件之水印文本框

步骤1:新建自定义控件,并继承TextBox类

 public partial class TTextBox : TextBox

步骤2:设置透明背景

透明背景
#region 透明背景
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);
protected override CreateParams CreateParams
{
    get
    {
        CreateParams prams = base.CreateParams;
        if (LoadLibrary("msftedit.dll") != IntPtr.Zero)
        {
            prams.ExStyle |= 0x020;
            prams.ClassName = "RICHEDIT50W";
        }
        return prams;
    }
}
#endregion

步骤3:设置水印

水印
#region 水印
private string _emptyTextTip;
private Color _emptyTextTipColor = Color.DarkGray;
private const int WM_PAINT = 0xF;

[DefaultValue("")]
public string EmptyTextTip
{
    get { return _emptyTextTip; }
    set
    {
        _emptyTextTip = value;
        base.Invalidate();
    }
}

[DefaultValue(typeof(Color), "DarkGray")]
public Color EmptyTextTipColor
{
    get { return _emptyTextTipColor; }
    set
    {
        _emptyTextTipColor = value;
        base.Invalidate();
    }
}

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);
    if (m.Msg == WM_PAINT)
    {
        WmPaint(ref m);
    }
}

private void WmPaint(ref Message m)
{
    using (Graphics graphics = Graphics.FromHwnd(base.Handle))
    {
        if (Text.Length == 0
            && !string.IsNullOrEmpty(_emptyTextTip)
            && !Focused)
        {
            TextFormatFlags format =
                TextFormatFlags.EndEllipsis |
                TextFormatFlags.VerticalCenter;

            if (RightToLeft == RightToLeft.Yes)
            {
                format |= TextFormatFlags.RightToLeft | TextFormatFlags.Right;
            }

            TextRenderer.DrawText(
                graphics,
                _emptyTextTip,
                Font,
                base.ClientRectangle,
                _emptyTextTipColor,
                format);
        }
    }
}
#endregion

步骤4:重新生成项目,打开设计页,在工具箱中的自定义控件拖拽即可.

 

posted @ 2019-11-05 17:24  ZainXiao  阅读(11)  评论(0编辑  收藏  举报