WinForm实现为TextBox设置水印文字功能

本文实例展示了WinForm实现为TextBox设置水印文字功能,非常实用的技巧,分享给大家供大家参考。

关键代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
 
namespace WinFormUtilHelpV2
{
   /// <summary>
   /// 基于.NET 2.0的TextBox工具类
   /// </summary>
   public static class TextBoxToolV2
   {
     private const int EM_SETCUEBANNER = 0x1501;
     [DllImport( "user32.dll" , CharSet = CharSet.Auto)]
 
     private static extern Int32 SendMessage
      (IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
 
     /// <summary>
     /// 为TextBox设置水印文字
     /// </summary>
     /// <param name="textBox">TextBox</param>
     /// <param name="watermark">水印文字</param>
     public static void SetWatermark( this TextBox textBox, string watermark)
     {
       SendMessage(textBox.Handle, EM_SETCUEBANNER, 0, watermark);
     }
     /// <summary>
     /// 清除水印文字
     /// </summary>
     /// <param name="textBox">TextBox</param>
     public static void ClearWatermark( this TextBox textBox)
     {
       SendMessage(textBox.Handle, EM_SETCUEBANNER, 0, string .Empty);
     }
   }
}

测试代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Windows.Forms;
using WinFormUtilHelpV2;
 
namespace WinFormUtilHelpV2Test
{
   public partial class WinTextBoxToolV2Test : Form
   {
     public WinTextBoxToolV2Test()
     {
       InitializeComponent();
     }
 
     private void WinTextBoxToolV2Test_Load( object sender, EventArgs e)
     {
       textBox1.SetWatermark( "请输入用户名称...." );
       textBox2.SetWatermark( "请输入用户密码...." );
     }
 
     private void button1_Click( object sender, EventArgs e)
     {
       textBox1.ClearWatermark();
       textBox2.ClearWatermark();
     }
   }
}

测试效果如下图所示:

希望本文所述的为TextBox设置水印文字功能示例对大家C#程序设计有所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值