废话不多说,直接上代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ControlLib
{
public class TextBoxEx : TextBox
{
private const int WM_PAINT = 0x000F;
private string backGroundText = "";
[Description("BackGround Text")]
public string BackGroundText
{
get { return backGroundText; }
set { backGroundText = value; }
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_PAINT)
{
using (Graphics g = CreateGraphics())
{
if (string.IsNullOrEmpty(Text) && !Focused)
{
SizeF size = g.MeasureString(backGroundText, Font);
//draw background text
g.DrawString(backGroundText, Font, Brushes.LightGray, new PointF(0, (Height - size.Height) / 2));
//System.Windows.Forms.TextFormatFlags flgFormat = (System.Windows.Forms.TextFormatFlags)0;
//flgFormat |= TextFormatFlags.NoPadding;
//TextRenderer.DrawText(g, m_Model.WatermarkText, Font, new Point(0, 0), m_Model.WatermarkColor, BackColor, flgFormat);
}
}
}
}
}
}
其实,还可以用这种方法在背景文本前面加上图标,再美化一下就可以做出和Win7系统登录界面上的文本框一样的效果了。