Make a shaped button in C#

This program's Load event handler confines 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 and then do not receive events such as clicks.

(An alternative strategy is to make a polygon or other shape and catch its Click event. 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.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.