需求:在实际开发中,由于TextBox控件的背景色样式不美观,且TextBox不能直接设置背景颜色,因此需要使用自定义控件以实现如下效果
实现代码
public partial class TxtLine : TextBox
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);
public TxtLine()
{
InitializeComponent();
this.Multiline = true;
this.Width = 100;
this.Height = 16;
this.BorderStyle = BorderStyle.None;
this.TextAlign = HorizontalAlignment.Center;
}
public string DataField
{ get; set; }
public string Description
{ get; set; }
private Color _linecolor = Color.Black;
public Color LineColor
{
get
{
return this._linecolor;
}
set
{
this._linecolor = value;
this.Invalidate();
}
}
private const int WM_PAINT = 0xF;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_PAINT)
{
DrawLine();
}
}
private void DrawLine()
{
Graphics g = this.CreateGraphics();
using (Pen p = new Pen(this._linecolor))
{
g.DrawLine(p, 0, this.Height - 1, this.Width, this.Height - 1);
}
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
protected override CreateParams CreateParams
{
get
{
CreateParams prams = base.CreateParams;
if (LoadLibrary("msftedit.dll") != IntPtr.Zero)
{
prams.ExStyle |= 0x020;
prams.ClassName = "RICHEDIT50W";
}
return prams;
}
}
}