[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make a shaped button in C#

example

This example shows how to make a shaped button in a Windows Forms C# project. It uses the following Load event handler to confine a Button control to a region to give it a non-rectangular shape.

// Shape the button. private void Form1_Load(object sender, EventArgs e) { // Define the points in the polygonal path. Point[] pts = { new Point( 20, 60), new Point(140, 60), new Point(140, 20), new Point(220, 100), new Point(140, 180), new Point(140, 140), new Point( 20, 140) }; // Make the GraphicsPath. GraphicsPath polygon_path = new GraphicsPath(FillMode.Winding); polygon_path.AddPolygon(pts); // Convert the GraphicsPath into a Region. Region polygon_region = new Region(polygon_path); // Constrain the button to the region. btnClickMe.Region = polygon_region; // Make the button big enough to hold the whole region. btnClickMe.SetBounds( btnClickMe.Location.X, btnClickMe.Location.Y, pts[3].X + 5, pts[4].Y + 5); }

The code makes an array of Point objects that define a polygonal shape for the button. It creates a GraphicsPath object and adds the polygon to it. It then converts the GraphicsPath into a Region and sets the button's Region property to the result.

Any parts of the Button that fall outside of the Region are clipped off so they are not drawn. They also don't receive events such as mouse clicks.

(An alternative strategy is to draw a polygon or other shape on a PictureBox and catch Click events that fall inside the shape. That works but doesn't give you the same features that a Button does. For example, it doesn't show a pressed appearance unless you write code to do it. This example's button automatically changes color when the user presses the mouse down on it.)

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.