8.3 Create an Irregularly Shaped Control


Problem

You need to create a nonrectangular form or control.

Solution

Create a new System.Drawing.Region object that has the shape you want for the form, and assign it to the Form.Region or the Control.Region property.

Discussion

To create a nonrectangular form or control, you first need to define the shape you want. The easiest approach is to use the System.Drawing.Drawing2D.GraphicsPath object, which can accommodate any combination of ellipses, rectangles, and closed curves. You can add shapes to a GraphicsPath instance using methods such as AddEllipse , AddRectangle , and AddClosedCurve . Once you are finished defining the shape you want, you can create a Region object from this GraphicsPath ” just submit the GraphicsPath in the Region class constructor. Finally, you can assign the Region to the Form.Region or Control.Region property.

In the example that follows , an irregularly shaped form (shown in Figure 8.3) is created using two curves made of multiple points, which are converted into a closed figure using the GraphicsPath.CloseAllFigures method.

 using System; using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; public class IrregularForm : System.Windows.Forms.Form {     private System.Windows.Forms.Button cmdClose;     private System.Windows.Forms.Label label1;     // (Designer code omitted.)     private void IrregularForm_Load(object sender, System.EventArgs e) {              GraphicsPath path = new GraphicsPath();         Point[] pointsA = new Point[] {new Point(0, 0),           new Point(40, 60), new Point(this.Width - 100, 10)};         path.AddCurve(pointsA);         Point[] pointsB = new Point[]           {new Point(this.Width - 40, this.Height - 60),             new Point(this.Width, this.Height),            new Point(10, this.Height)};         path.AddCurve(pointsB);         path.CloseAllFigures();         this.Region = new Region(path);     }     private void cmdClose_Click(object sender, System.EventArgs e) {              this.Close();     } } 

Figure 8.3: A nonrectangular form.

For an example that demonstrates a nonrectangular control, refer to recipe 8.4.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net