C# Form with custom border and rounded edges [dupl

2019-01-12 02:56发布

问题:

This question already has an answer here:

  • How to Draw a Rounded Rectangle with WinForms (.NET)? 5 answers

I am using this code to make my form (FormBorderStyle=none) with rounded edges:

[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
    int nLeftRect, // x-coordinate of upper-left corner
    int nTopRect, // y-coordinate of upper-left corner
    int nRightRect, // x-coordinate of lower-right corner
    int nBottomRect, // y-coordinate of lower-right corner
    int nWidthEllipse, // height of ellipse
    int nHeightEllipse // width of ellipse
 );

public Form1()
{
    InitializeComponent();
    Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
}

And this to set a custom border on the Paint event:

    ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Black, 5, ButtonBorderStyle.Solid, Color.Black, 5, ButtonBorderStyle.Solid, Color.Black, 5, ButtonBorderStyle.Solid, Color.Black, 5, ButtonBorderStyle.Solid);

But see this .

The inside form rectangle doesn't have rounded edges.

How can I make the blue inside form rectangle to have rounded edge too so it wont look like the screenshot?

回答1:

The Region propery simply cuts off the corners. To have a true rounded corner you will have to draw the rounded rectangles.

Drawing rounded rectangles

It might be easier to draw an image of the shape you want and put that on the transparent form. Easier to draw but cannot be resized.



回答2:

Note you're leaking the handle returned by CreateRoundRectRgn(), you should free it with DeleteObject() after it is used.

The Region.FromHrgn() copies the definition, so it won't free the handle.

[DllImport("Gdi32.dll", EntryPoint = "DeleteObject")]
public static extern bool DeleteObject(IntPtr hObject);

public Form1()
{
    InitializeComponent();
    IntPtr handle = CreateRoundRectRgn(0, 0, Width, Height, 20, 20);
    if (handle == IntPtr.Zero)
        ; // error with CreateRoundRectRgn
    Region = System.Drawing.Region.FromHrgn(handle);
    DeleteObject(handle);
}

(would add as comment but reputation is ded)