Owner Draw ComboBox
Article By : Shripad Kulkarni
Download : Source Code
Executable : Exe

To do some custom drawing and painting with any of the windows controls, you need to do the drawing of the control yourself. The "OwnerDraw" property of the control will allow you to accomplish this. In this article we will try to custom draw a ComboBox..

Step 1: Create a simple windows form project and add a combo box from the windows control toolbox into the form.
In the properties for the combobox set the DrawMode option to "OwnerDrawFixed".

When the item is owner drawn , the application will send the DrawItem & MeasureItem event to allow us to do all the custom drawing.

		private void comboBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)

For every item that needs to be drawn the DrawItemEventArgs parameter will contain the index of the item to draw. It also contains the graphics
object that we will use to do all the drawing and painting. Here is a simple example ( The Font Combo Box ) 
		private void comboBox2_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
		{
			Graphics g = e.Graphics ;
		    Rectangle r = e.Bounds ;

			if ( e.Index >= 0 ) 
			{
				Rectangle rd = r ; 
				rd.Width = rd.Left + 100 ; 
				
				Rectangle rt = r ;
				r.X = rd.Right ; 

				SolidBrush b = (SolidBrush)colorArray[e.Index];
				g.FillRectangle(b  , rd);
				StringFormat sf = new StringFormat();
				sf.Alignment = StringAlignment.Near;

				Console.WriteLine(e.State.ToString());
				e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Black), 2 ), r );
				if ( e.State == ( DrawItemState.NoAccelerator | DrawItemState.NoFocusRect))
				{
					e.Graphics.FillRectangle(new SolidBrush(Color.White) , r);
					e.Graphics.DrawString( b.Color.Name, new Font("Ariel" , 8 , FontStyle.Bold  ) , new SolidBrush(Color.Black), r ,sf);
					e.DrawFocusRectangle();
				}
				else
				{
					e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue) , r);
					e.Graphics.DrawString( b.Color.Name, new Font("Veranda" , 12 , FontStyle.Bold  ) , new SolidBrush(Color.Red), r ,sf);
					e.DrawFocusRectangle();
				}
			}
		}
For a OwnerDrawFixed property the MeasureItem function will have no effect. This function will be activated only for the OwnerDrawVariable item.