[WinForm]为TextBox设置水印文字_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > [WinForm]为TextBox设置水印文字

[WinForm]为TextBox设置水印文字

 2014/8/7 11:06:37  楚人游子  程序员俱乐部  我要评论(0)
  • 摘要:关键代码:usingSystem;usingSystem.Runtime.InteropServices;usingSystem.Windows.Forms;namespaceWinFormUtilHelpV2{///<summary>///基于.NET2.0的TextBox工具类///</summary>publicstaticclassTextBoxToolV2{privateconstintEM_SETCUEBANNER=0x1501;[DllImport
  • 标签:for winform

关键代码:

class="csharpcode">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);
        }
    }
}

测试代码:

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();
        }
    }
}

测试效果:

image

希望有所帮助!

发表评论
用户名: 匿名