C# Form with custom border and rounded edges [dupl

2019-01-12 03:23发布

This question already has an answer here:

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

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?

2条回答
可以哭但决不认输i
2楼-- · 2019-01-12 03:34

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)

查看更多
别忘想泡老子
3楼-- · 2019-01-12 03:42

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.

查看更多
登录 后发表回答