自定义控件之带水印的Textbox

时间:2022-07-05 13:48:58

代码地址:

http://download.csdn.net/detail/u010312811/9553195

Windows消息处理:

http://www.cnblogs.com/imstrive/p/5596030.html

自定义控件之带水印的Textbox

1.私有变量

 //水印文字
private string _waterText = String.Empty;
//水印颜色
private Color _waterColor = Color.DarkGray;

2.属性

 /// <summary>
/// 水印文字
/// </summary>
[Description("水印文字"),Category("SLT")]
public string WaterText
{
get { return _waterText; }
set { _waterText = value; }
}
/// <summary>
/// 水印颜色
/// </summary>
[Description("水印文字"),Category("SLT")]
public Color WaterColor
{
get { return _waterColor; }
set { _waterColor = value; }
}

3.Override Methods

 protected override void WndProc(ref Message m)
{
base.WndProc(ref m); if (m.Msg == (int)WindowsMessage.WM_PAINT)
{
WmPaintWater(ref m);
}
}

4.方法

 private void WmPaintWater(ref Message m)
{
//获取控件绑定到的窗口句柄
using (Graphics g = Graphics.FromHwnd(base.Handle))
{
if (string.IsNullOrEmpty(this.Text) && !String.IsNullOrEmpty(this.WaterText) && !this.Focused)
{
TextFormatFlags flags = TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter;
TextRenderer.DrawText(g, WaterText, this.Font, this.ClientRectangle, WaterColor, flags);
}
}
}