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

摘要:
在一些软件中,我们看到当输入控件没有输入和焦点时,会显示一些提示消息。互联网上有一些介绍使用复合控件来实现它。事实上,通过直接继承文本框控件很容易实现它。步骤3:最重要的步骤是重写wndproc函数并截取wm_Paint消息。当没有输入内容和输入焦点时,重新绘制文本框。查看以下代码:protectedoverridevoidwndproc{base.wndpror;if{wmpaint;}}privatevoidwmpaint{rectangle矩形=new矩形;使用{if(text.length==0&&!

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

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

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

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

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

protected override void wndproc(refmessage m)
{
    base.wndproc(refm);
    if (m.msg ==wm_paint)
    {
        wmpaint(refm);
    }
}
 
private void wmpaint(refmessage 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);
          }
       }

免责声明:文章转载自《C# WinForm控件美化扩展系列之给TextBox加水印》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Oracle数据exp时报ORA-29275问题解决——字符集不一致Spring Boot + Spring Cloud 实现权限管理系统 (Spring Security 版本 )下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

WinForm 限制同一个进程只能打开一次

打开Program.cs 代码文件,这里是程序的入口点,如下: static voidMain() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false)...

C# WinForm遍历窗体控件的3种方法

C# WinForm遍历窗体控件的3种方法 转 https://www.cnblogs.com/zhaoshujie/p/14638460.html 1.循环遍历 private void GetControls(Control fatherControl) { Control.ControlCollection sonControls = fa...

winform(四)——简单计算器制作

效果图: 代码区: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; usin...

winform 父窗体与子窗体数据传递

简单实例截图: 父窗体代码如下: public partial class Form1 : Form{Child2 child2 = new Child2();public Form1(){InitializeComponent();child2.receive += new Child2.receiveData(testReceive);} privat...

winform窗体(五)——布局方式

一、默认布局 ★可以加panel,也可以不加; ★通过鼠标拖动控件的方式,根据自己的想法布局。拖动控件的过程中,会有对齐的线,方便操作; ★也可选中要布局的控件,在工具栏中有对齐工具可供选择,也有调整各个控件大小的工具。 注:分层:右键点击控件。可以选择置于顶层或置于顶层。       锁定控件:当部分布局完成,为了操作失误,把布局好的打乱,可以选中布局...

扩展WinForm的ComboBox

个人认为winform的combobox不是那么的好用,所以自己扩展了一下。重新定义Items属性,并且支持树结构。为每项加入了CheckBox状态。丰富的列表项类ListItem。效果如图:代码清单: {[Designer(typeof(ControlDesigner))]publicclassComboBox:System.Windows.Forms....