(C#)Winform修改DateTimePicker控件的背景色Winform中日期控件DateTimePicker默认是不能修改背景色和边框色的,如果想要改变它的背景色和边框色
那也是有办法的,只需要继承DateTimePicker做一个自定义控件,再重写WndProc方法。此外还要重写属性,这样就可以在外部修改它的颜色了。 自定义控件的完整代码如下:
public class UCDateTime : DateTimePicker
{
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, object lParam);
[DllImport("user32")]
private static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
const int WM_ERASEBKGND = 0x14;
const int WM_NC_PAINT = 0x85;
const int WM_PAINT = 0xF;
const int WM_PRINTCLIENT = 0x318;
//边框颜色
private Pen BorderPen = new Pen(SystemColors.ControlDark, 2);
/// <summary>
/// 定义背景色私有变量
/// </summary>
private Color _backColor = Color.White;
/// <summary>
/// 定义背景色属性
/// </summary>
public override Color BackColor
{
get
{
return _backColor;
}
set
{
_backColor = value;
}
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
IntPtr hDC = IntPtr.Zero;
Graphics gdc = null;
switch (m.Msg)
{
//画背景色
case WM_ERASEBKGND:
gdc = Graphics.FromHdc(m.WParam);
gdc.FillRectangle(new SolidBrush(_backColor), new Rectangle(0, 0, this.Width, this.Height));
gdc.Dispose();
break;
case WM_NC_PAINT:
hDC = GetWindowDC(m.HWnd);
gdc = Graphics.FromHdc(hDC);
SendMessage(this.Handle, WM_ERASEBKGND, hDC, 0);
SendPrintClientMsg();
SendMessage(this.Handle, WM_PAINT, IntPtr.Zero, 0);
m.Result = (IntPtr)1; // indicate msg has been processed
ReleaseDC(m.HWnd, hDC);
gdc.Dispose();
break;
//画边框
case WM_PAINT:
base.WndProc(ref m);
hDC = GetWindowDC(m.HWnd);
gdc = Graphics.FromHdc(hDC);
OverrideControlBorder(gdc);
ReleaseDC(m.HWnd, hDC);
gdc.Dispose();
break;
default:
base.WndProc(ref m);
break;
}
}
private void SendPrintClientMsg()
{
// We send this message for the control to redraw the client area
Graphics gClient = this.CreateGraphics();
IntPtr ptrClientDC = gClient.GetHdc();
SendMessage(this.Handle, WM_PRINTCLIENT, ptrClientDC, 0);
gClient.ReleaseHdc(ptrClientDC);
gClient.Dispose();
}
private void OverrideControlBorder(Graphics g)
{
g.DrawRectangle(BorderPen, new Rectangle(0, 0, this.Width, this.Height));
}
}
相关文章
- C# WinForm控件TrackBar与ProgressBar及Timer的用法
- c#(winform,webform通用)利用npoi将xls文件复制为xlsx文件(excel的修改,保存,包括excel2003-office2007+的处理)
- c#设置button、label等控件的背景色为透明
- C# WinForm中自定义了一个控件,在Form中放了一个button,如何实现按下button之后,让自定义的控件响应?
- C# winform去掉ToolStripDropDown的外边框设定背景图片(有透明度的图片PNG)之后设定背景色透明
- C# winform 为什么用dateTimePicker控件查询只能查询到月份,日那里就查询不了???
- C# 的界面控件属性修改线程安全问题
- MFC中的Date Time Picker控件如何修改背景色?
- Visual Studio C#的winform/webform/asp.net控件命名规范
- C# WinForm窗体控件Panel修改边框颜色以及边框宽度方法