<$BlogRSDURL$>
My Blog Links
Site Links
Currently Reading
Blogroll
Archives
Tools
  • This page is powered by Blogger. Isn't yours?
  • Weblog Commenting and Trackback by HaloScan.com
  • 2RSS.com :: RSS directory
  • Listed on BlogShares
  • Blog Directory, Find A Blog, Submit A Blog, Search For The Best Blogs

Friday, March 12, 2004

FlatComboBox Sample 

After working on the FlatTabControl, I decided to look at making the WinForms ComboBox flat (it doesn't support a flat look either) using the same trick of setting the ControlStyles.UserPaint style to true, and drawing in the borders myself.



Overall, it worked pretty well, and I followed the same pattern with the OnPaint, breaking it up into different, overridable steps:

  • DrawControlBorder
  • DrawDropDownButton

This painted in the border and button correctly. However, the edit portion of the ComboBox wouldn't draw correctly. For a ComboBox in DropDownList style, I just had the selected item draw in the top portion as well. That worked, but for the DropDrown and Simple styles, the edit control which exists within the ComboBox would try to paint itself. And, it would paint itself with the wrong font and colors.

It took awhile, but I found a work-around for painting the edit area correctly too. The first part was setting that control's font correctly, which I did in an override of OnHandleCreated:

protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);

// Find the edit control within the ComboBox.
if (DropDownStyle != ComboBoxStyle.DropDownList)
{
IntPtr hEditControl = Win32Methods.GetDlgItem(Handle, editControlId);
Debug.Assert(hEditControl != IntPtr.Zero,
"Failed to get ComboBox's edit control");

// make sure the edit control in the combo box has the right font setting.
Win32Methods.SendMessage(hEditControl, Win32Methods.WM_SETFONT,
Font.ToHfont(), true);
}
...
}

In that code, we find the handle to the EditControl within a ComboBox and set its font the old fashioned way -- through a Win32 API call for SendMessage for WM_SETFONT.

Well, that worked like a charm, so I tried some similar Win32 magic for the colors. I overrode the WndProc and intercepted the WM_CTLCOLOREDIT and WM_CTLCOLORLISTBOX messages. These are sent when a Win32 control is about to paint, so that you can change the colors at that time. So, I created a virtual OnCtlColor method to handle those window messages in my FlatComboBox control.

protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
// when the combo box edit and list controls ask for what colors they
// need, then call OnCtlColor for our FlatComboBox.
case Win32Methods.WM_CTLCOLOREDIT:
case Win32Methods.WM_CTLCOLORLISTBOX:
m.Result = OnCtlColor(m.WParam, m.Msg);
break;
default:
base.WndProc (ref m);
break;
}
}
#endregion

protected virtual IntPtr OnCtlColor(IntPtr hDC, int msg)
{
// Set the appropriate text and background color in the painting DC for
// the edit control. This BkColor is just used for the background right
// around the text.

// *** Note: this is when it's helpful to have a background in Win32 programming
// even when working with .NET, because these are the message that you need to
// handle and the GDI calls you need to make in Win32 to get a combo box control
// to paint in custom colors.
Win32Methods.SetTextColor(hDC, ColorTranslator.ToWin32(ForeColor));
Win32Methods.SetBkColor(hDC, ColorTranslator.ToWin32(BackColor));

// return an HBRUSH to be used to paint the background of the control.
// this is for the portion of the control that may not have text in it.
return BackgroundBrush;
}

This code goes and sets the text and background colors to the ones specified for the control, so that the edit portion paints exactly the same as the rest of the control.

Note: As you see in the picture above, the border for the list portion of the Simple ComboBox is still paint with the default border. There is probably a way to paint that as well by taking over the painting of the list; however, it's not something I needed for my use, so I left it as an exercise for the reader... :)

The code for this sample makes several calls to Win32 APIs which I call through PInvoke interoperability, which I encapsulated into a Win32Methods class. You can get the full source code for those methods and constants from the sample download on GotDotNet or look at it online and report bugs at the workspace.

Comments:
Возведение жилых и индустриальных многоуровневых объектов влечет за собой привлечение особой строительной техники, оснащенной для проведения конкретных задач. Исполнение строительных работ происходит по стадиям, в связи, с чем, задействовать строительную технику тоже приходится по шагам, в зависимости от поставленных задач.
Но закупка такой специальной техники влечет большие затраты. Так как стоит она дорого, компания "Сапрос" предлагает услуги аренды строительной техники. Наш автопарк укомплектован всем надобным для строительства автотранспортом. Моментальный заказ спецтехники можно сделать через интернет, заполнив заявку онлайн на сайте компании. В Самаре мы пользуемя популярностью именно за высококачесвенное и оперативное сопровождение заказчиков, предоставляя такую услугу, как гидромолот аренда. Наши специалисты при необходимости в полном объеме проконсультируют Вас о более подходящем под запросы автотранспорте, что позволит сэкономить и время и финансы.
Sapros Ru - [url=http://sapros.ru]аренда бары[/url]
 
Кабельная продукция - один из основных продуктов, применяемых для полнофункциональной деятельности электрооборудования. Многообразие моделей и марок кабеля на сайте ООО "Спецкомплект" предоставляют широкий выбор для оптового и розничного заказчика.
Компания предлагает ассортимент популярных товаров, таких как К1163, К1150, К1151, К1152, Арматура для СИП ENSTO, КВВГ, КВбБШв, АС,ДКС, оптический кабель ОКГ, ОКБ, ОКЛ, ОКК.
Щитовое оборудование высокого качества по доступной цене, смотрите обзор на сайте компании.
Specomplect.ru - [url=http://specomplect.ru]лотки К1154[/url]
 
Post a Comment