廢話不多說,直接上代碼:
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系統登錄界面上的文本框一樣的效果了。