Make a shaped form by setting its region in C#


In theory you can make a shaped form by setting its 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();

    // 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.

Parts of the form that lie outside of the region are clipped so they don’t appear and don’t respond to mouse events. The form’s system commands still work, however, so you can still close the form by pressing Alt+F4.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in forms, user interface and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *