Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘winform’

WinForms :: Get subitems in Menu programmatically

Posted by Jean Paul on November 11, 2011

This is a small piece of code to iterate over menu sub items dynamically. The topic was generated from a forum fix and I thought it will be a good idea to blog it.

/* Place a menu strip control with File and Edit as the top level items.  Inside the File menu add 3 subitems.  Those items can be viewed dynamically using the following code */


MenuStrip menuStrip = this.Controls.Cast<Control>().Where(c => (c is MenuStrip)).FirstOrDefault() as MenuStrip;
if (menuStrip != null)
ToolStripMenuItem menuItem = menuStrip.Items.Cast<ToolStripMenuItem>().Where(mi => mi.Text.Replace("&", string.Empty).ToLower() == "file").FirstOrDefault() as ToolStripMenuItem;
foreach (ToolStripItem item in menuItem.DropDown.Items)


Posted in C# | Tagged: , , , , | Leave a Comment »

ColorComboBox to pick colors

Posted by Jean Paul on January 12, 2011

In this short article, I am trying to create a ColorComboBox control which allows the user to select colors from System.Drawing.Color struct. From Mahesh Chand’s color code snippet, I was inspired about the idea of listing color using reflection. So I thought it would be good if we can convert the code into a control.


The end control is shown in the snap shot below:


Steps involved in creating Control

The article is been subdivided into creating the custom combobox class and implementing the draw events.

Part 1: Create Custom ColorComboBox

For this, we have to create a new class and change the base class to ComboBox.

public class ColorComboBox : ComboBox

Part 2: Modify the constructor

We need to modify the constructor to fill the ComboBox with colors and change the draw mode.

public ColorComboBox()



// Change DrawMode for custom drawing

this.DrawMode = DrawMode.OwnerDrawFixed;

this.DropDownStyle = ComboBoxStyle.DropDownList;


Part 3: Implement the FillColors() method

For loading the combobox with color items, we need to use .Net Reflection. Following is the code to get all Color properties from struct Color.

private void FillColors()



// Fill Colors using Reflection

foreach (Color color in typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public).Where(c => c.PropertyType == typeof(Color)).Select(c => (Color)c.GetValue(c, null)))





For reduction of code I have used Lambda Expressions. Basically the code will iterate through all the properties which are static and public, then the Where() method will filter them by type of Color. The Select() method converts the PropetyInfo to Color object using c.GetValue() method.

Part 4: Custom Draw the control

Now we are good with the entire color items in the list. The next challenge is to display the item with the actual color filled in a rectangle and showing the color name next to it.

For this we have to override the OnDrawItem method of combobox.

protected override void OnDrawItem(DrawItemEventArgs e)


if (e.Index >= 0)


Color color = (Color)this.Items[e.Index];

int nextX = 0;

e.Graphics.FillRectangle(new SolidBrush(e.BackColor), e.Bounds);

DrawColor(e, color, ref nextX);

DrawText(e, color, nextX);





Whenever the ComboBox item is painted the above OnDrawItem() method will be called. We basically checks whether the e.Index >= 0 to ensure there is a valid item in the list and do the custom drawing.

The drawing is divided into 3 steps.

1. Paint the Background

2. Draw the Color

3. Draw the Text (color name)

Part 5: Add Property to get selected color

Now we need to add a new property to get/set the selected color.

public Color Color




if (this.SelectedItem != null)

return (Color)this.SelectedItem;

return Color.Black;




int ix = this.Items.IndexOf(value);

if (ix >= 0)

this.SelectedIndex = ix;



The above get code will return the selected color by converting selected item into Color struct.

The set code will allow us to set the selected color by taking the set value and iterating through the items in the combobox.

Using the Code

The attachment contains the ColorComboBox as well as the test form. For reusing the control, one may take the ColorComboBox file alone and can be integrated to other projects.

Posted in C# | Tagged: , , , | Leave a Comment »

WinForms: How to create a control from another thread?

Posted by Jean Paul on October 28, 2010

Control.CheckForIllegalCrossThreadCalls = false; is needed for refreshing controsl from other threads.

But for creating controls and setting parent to other control which was created in another thread the following code is needed.


Create a new windows forms application and place a button with click event handler on it.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Threading;


namespace WindowsFormsApplication1


    public partial class Form1 : Form


        public Form1()





        public delegate void DelegateDefinition();


        private void button1_Click(object sender, EventArgs e)


            DelegateDefinition delgate = new DelegateDefinition(CreateButton);

            ThreadStart threadStart = new ThreadStart(delegate { this.BeginInvoke(delgate); });

            Thread thread = new Thread(threadStart);




        public void CreateButton()


            Button button = new Button();

            button.Parent = this;

            button.Location = new Point(10, 10);

            button.Size = new Size(200, 25);

            button.Text = "Hi! I am the new button";





Posted in WinForms | Tagged: , , | Leave a Comment »

Global Exception Handler in WinForms

Posted by Jean Paul on October 12, 2010

This is a small code snippet to set the global exception handler in Windows Forms application.

Setting a global exception handler can help us in logging the exceptions to a common file, show them to the user in a friendly way or email to the moderator.

// Place the code inside Program.cs, before Application.Run

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);


public static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    // Process the e.Exception
    MessageBox.Show("I got the exception!");

Posted in WinForms | Tagged: , , | Leave a Comment »