Donate

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.
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));
 }
}
Output
Custom DateTimePicker Control With Background Color And Icon In WIndows Forms
The source is available in Github. :-)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.