Custom DateTimePicker Control With Background Color And Icon In Windows Forms
Hello
Here's a custom DateTimePicker with background color and image icon instead of using the ComboBoxRenderer class. The icon is an image that is added to the project as part of it's resource. The adding of icon is processed through the WndProc method while the setting of background color is handled in the OnPaint() event. Notice that in the constructor, the SetStyle()'s parameters are ControlStyles.UserPaint so that the control paints itself and true to apply the specified style to the control.
Output
The source is available in Github. :-)
Here's a custom DateTimePicker with background color and image icon instead of using the ComboBoxRenderer class. The icon is an image that is added to the project as part of it's resource. The adding of icon is processed through the WndProc method while the setting of background color is handled in the OnPaint() event. Notice that in the constructor, the SetStyle()'s parameters are ControlStyles.UserPaint so that the control paints itself and true to apply the specified style to the control.
public class DateTimePickerWithBackground : DateTimePicker { private Bitmap _bmp; enum BorderSize { One = 1, Two = 2 }; public DateTimePickerWithBackground() { _bmp = new Bitmap(ClientRectangle.Height, ClientRectangle.Width); this.SetStyle(ControlStyles.UserPaint, true); } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0xf) //WM_PAINT message { Graphics g = Graphics.FromHwnd(m.HWnd); g.DrawImage(_bmp, ClientRectangle.Width - Convert.ToInt32(9 * ClientRectangle.Width / 100), 2); g.Dispose(); } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.FillRectangle(new SolidBrush(Color.LawnGreen), ClientRectangle); ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Color.LightGray, (int)BorderSize.One, ButtonBorderStyle.Solid, Color.LightGray, (int)BorderSize.One, ButtonBorderStyle.Solid, Color.LightGray, (int)BorderSize.One, ButtonBorderStyle.Solid, Color.LightGray, (int)BorderSize.One, ButtonBorderStyle.Solid); TextRenderer.DrawText(e.Graphics, Text, Font, Rectangle.FromLTRB(0, 0, Width - Height, Height), SystemColors.ControlText); Image img = Properties.Resources.calendar_picker; _bmp = new Bitmap(img, new Size(img.Width, img.Height)); } }
The source is available in Github. :-)
Comments
Post a Comment