C# WinForm控件美化扩展系列之给TextBox加水印

在一些软件中,我们看到当一个输入控件(textbox)没有输入而且没有焦点的时候,会显示一些提示信息,网上有一些介绍用复合控件来实现,其实我们直接继承textbox控件也很容易实现。

下面就介绍怎样来实现这个控件。

第一步:我们建一个继承 textbox 的类,命名为watermaktextbox。

第二步:给这个类添加两个属性,一个是emptytexttip,就是当控件没有输入内容和没有焦点的时候显示的提示文本,也就是水印了;另一个是emptytexttipcolor,就是提示文本的颜色。

第三步:也就是最重要的一步,就是重写wndproc 函数,截取wm_paint消息,当没有输入内容和输入焦点时,重绘textbox,看下面的代码:

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)
{
    rectangle rectangle = new rectangle(0, 0, width, height);
    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);
          }
       }

 

posted @ 2015-05-22 13:31  路过相遇错过  阅读(2281)  评论(0编辑  收藏  举报