[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 form by setting its region in C#

example

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(); 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.

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 the example to experiment with it and to see additional details.

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