Give a form a shape by setting its region in C#

In theory you can set a form's TransparencyKey property to make parts of the form disappear. In practice, this feature has gotten buggy in recent versions of .NET so it doesn't always work consistently on every computer.

An alternative is to create a region that defines the form's shape and then set the form's Region property to the region.

The example program uses the following code to give its form a star shape.

private void Form1_Load(object sender, EventArgs e)
{
// Make points to define a polygon for the form.
PointF[] pts = new PointF[10];
float cx = (float)(this.ClientSize.Width * 0.5);
float cy = (float)(this.ClientSize.Height * 0.5);
float r1 = (float)(this.ClientSize.Height * 0.45);
float r2 = (float)(this.ClientSize.Height * 0.25);
float theta = (float)(-Math.PI / 2);
float dtheta = (float)(2 * Math.PI / 10);
for (int i = 0; i < 10; i += 2)
{
pts[i] = new PointF(
(float)(cx + r1 * Math.Cos(theta)),
(float)(cy + r1 * Math.Sin(theta)));
theta += dtheta;
pts[i + 1] = new PointF(
(float)(cx + r2 * Math.Cos(theta)),
(float)(cy + r2 * Math.Sin(theta)));
theta += dtheta;
}

// Use the polygon to define a GraphicsPath.
GraphicsPath path = new GraphicsPath();
path.AddPolygon(pts);

// Make a region from the path.
Region form_region = new Region(path);

// Restrict the form to the region.
this.Region = form_region;
}

The code uses a loop to initialize an array with the points that define a star. It creates a GraphicsPath and uses its AddPolygon method to add the polygon defined by the points to the path. It then creates a Region based on the GraphicsPath and sets the form's Region property.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

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.