为textbox控件添加水印

来源:互联网 发布:电脑办公软件大全 编辑:程序博客网 时间:2024/05/16 12:36

在工程中新建一个类内容如下:

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上面添加一个标签控件


 


0 0
原创粉丝点击