Many flat combobox controls out there are not based on the standard
ComboBox control that is supplied by .NET, instead they have their own interfaces and requires a customized type of
ComboBoxItem when inserting into the
Items container. If you already have code written based on the standard .NET
ComboBox, changing to the flat look may also require you to modify your codes. I have personally experienced that as a problem, and someone else has brought that up as a problem as well in my recent article DateTimePicker appears Flat. Many of the information provided here may appear in the DateTimePicker appears Flat article already, or maybe explained better in there, so please check it out.
Using the Class
This class inherits from
ComboBox, therefore you can use it in exactly the same way as the
ComboBox control or even as a replacement.
So instead of doing this:
ComboBox cmb = new ComboBox();
You will do:
ComboBox cmb = new FlatComboBox();
FlatComboBox cmb = new FlatComboBox();
That is how simple it is :)
To achieve the flat look for the control, I have to override the
WndProc method, which is the method that processes through all the window messages for this control. We are particularly interested with
IntPtr hDC = GetWindowDC(this.Handle);
Graphics gdc = Graphics.FromHdc(hDC);
SendMessage(this.Handle, WM_ERASEBKGND, hDC, 0);
m.Result = (IntPtr) 1;
Pen p = new Pen((this.Enabled? BackColor:SystemColors.Control), 2);
gdc.DrawRectangle(p, new Rectangle(2, 2, this.Width-3, this.Height-3));
WM_NC_PAINT message is received when the control needs to paint its border. Here I trapped the message and send
WM_PRINTCLIENT message so that the
ComboBox will draw its client area properly, then followed by drawing a flat border around it.
WM_PAINT message is received when the control needs to paint portion of its windows.
ComboBox internally embeds a textbox and will draw the textbox with 3D border. A quick way to achieve the flat look is to paint a rectangle overlaying the 3D border of the textbox, therefore it will appear flat. We then paint the flat dropdown and border over it. Overriding the border is optional here, but I did it for the user experience where if the control is in focus, it will have a black line border or otherwise none.
FlatComboBox does not draw with
ComboBox.Simple style. When this style is set for the
ComboBox object, this class will let the base class perform the standard drawing.
- 18 May 2005
DROPDOWNWIDTH value is dynamic now based on the system setting hence will work well in different screen resolutions.
- Only acquires and creates window DC when necessary.