using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace KK.WatermarkTextBox { public partial class WatermarkTextBox : TextBox { private const uint ECM_FIRST = 0x1500; private const uint EM_SETCUEBANNER = ECM_FIRST + 1; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); public WatermarkTextBox() { InitializeComponent(); } private string watermarkText; public string WatermarkText { get { return watermarkText; } set { watermarkText = value; SetWatermark(watermarkText); } } private void SetWatermark(string watermarkText) { SendMessage(this.Handle, EM_SETCUEBANNER, 0, watermarkText); } } }
using System.Drawing; using System.Windows.Forms; namespace KK.WaterMark.Control { public partial class WaterMarkTextBox : TextBox { private string watermarkText; public string WatermarkText { get { return watermarkText; } set { watermarkText = value; } } private Color watermarkTextColor; public Color WatermarkTextColor { get { return watermarkTextColor; } set { watermarkTextColor = value; } } public WaterMarkTextBox() { InitializeComponent(); } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg ==0x000F )//WM_PAINT { WmPaint(ref m); } } private void WmPaint(ref Message m) { Rectangle rectangle = new Rectangle(0, 0, Width, Height); using (Graphics graphics = Graphics.FromHwnd(base.Handle)) { if (Text.Length == 0 && !string.IsNullOrEmpty(watermarkText) && !Focused) { TextFormatFlags format = TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) { format |= TextFormatFlags.RightToLeft | TextFormatFlags.Right; } TextRenderer.DrawText(graphics, watermarkText, Font, base.ClientRectangle, watermarkTextColor, format); } } } } }
标签:string,提示,System,文本框,private,watermarkText,using,public,输入 From: https://www.cnblogs.com/YYkun/p/16853882.html