Custom shaped controls in C# — using GraphicsPath

Have you ever thought of having a circular button, triangular form, amoebic labels ?? Doing all these in C# is really simple and cool. All you need to do is, use the Region property of the control to change the shape. Lets try to change the shape of a button to ellipse.

  • Create a new button the usual way.

System.Windows.Forms.Button myButton = new System.Windows.Forms.Button();

  • Change the color of the button to distinguish it from the form’s background.

myButton.BackColor = Color.Blue; //Lets change the color

  • Increase the size of the button.

myButton.Size = new Size(100, 100);

  • Create a GraphicsPath object to define a custom path which will be associated with the button’s region in the next step. There are loads of methods like AddEllipse(). Try AddPloygon() which takes a set of points.

System.Drawing.Drawing2D.GraphicsPath aGraphicsPath = new System.Drawing.Drawing2D.GraphicsPath(); //The GraphicsPath class allows us to define custom paths

myGraphicsPath.AddEllipse(5, 5, 90, 90); //A big circle

  • Associate the GraphicsPath with the button’s Region property.

myButton.Region = new Region(aGraphicsPath); //Associating the path made by us to the button's region

Run the application and see for your self, a rounded button. Cool, isn’t it ? Play with GraphicsPath to create custom shaped controls.

Tags: , ,

4 comments

  1. Thanks, really helpful and clear post with nice comments to the code.

  2. Very nice, yet simple solution.

  3. Very Nice

  4. this was very helpfull.. thanks… does anyone know how to create puzzle shaped buttons?

Leave a comment