Background color of DateTime Picker control

  • Thread starter Thread starter eljainc
  • Start date Start date
E

eljainc

Hello,

I'm trying to change the background color of a DateTimePicker control.
I tried changing the background, but only the calendar colors seem to
be the only thing that can be changed as far as colors go. How can I
change this color? Or do I need to use a different type of control to
enter a date. I want to enter the date in short form (MM/DD/YYYY).

Mike McWhinney
elja, Inc.
 
Color is the tricky bit; I have ported from
[http://dotnet.mvps.org/dotnet/faqs/?id=datetimepickerbackcolor&lang=en]
(by Herfried K. Wagner) for you below. Usage first:

using(Form f = new Form())
using (DateTimePicker dtp = new ExtendedDateTimePicker()) {
dtp.Format = DateTimePickerFormat.Custom;
// maybe "d" would do for next
dtp.CustomFormat =
CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
dtp.BackColor = Color.LightBlue;
f.Controls.Add(dtp);
f.ShowDialog();
}

====== snip ======

public class ExtendedDateTimePicker : DateTimePicker {
private SolidBrush _backBrush;

public ExtendedDateTimePicker() : base() {
BackColor = base.BackColor;
}
[Browsable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override Color BackColor {
get { return base.BackColor; }
set {
base.BackColor = value;
DestroyBrush();
Invalidate();
}
}

protected override void WndProc(ref Message m) {
const int WM_ERASEBKGND = 20;
if (m.Msg == WM_ERASEBKGND) {
using (Graphics g = Graphics.FromHdc(m.WParam)) {
if (_backBrush == null) {
_backBrush = new SolidBrush(BackColor);
}
g.FillRectangle(_backBrush, ClientRectangle);
}
} else {
base.WndProc(ref m);
}
}
protected override void Dispose(bool disposing) {
DestroyBrush();
base.Dispose(disposing);
}
private void DestroyBrush() {
if (_backBrush != null) {
_backBrush.Dispose();
_backBrush = null;
}
}
}
 
Oops; slightly wrong version in clipboard; you can drop the
constructor, and Dispose() should read:

protected override void Dispose(bool disposing) {
if (disposing) { DestroyBrush(); }
base.Dispose(disposing);
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top