在工程中新建一个类内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace LLSbasicdlg
{
public static class textwater
{
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);
}
}
}
工程中其他项目都可以使用该方法进行设置,要求.net框架为4.0;
引用方法为this.textbox1.SetWatermark(“测试成功");
另一种适用于非.net4.0
控件初始化添加事件
在textbox上面添加一个标签控件