带有自定义边框和圆边的C#表单

时间:2011-02-23 14:29:54

标签: c# winforms rounded-corners formborderstyle

我正在使用此代码制作带有圆边的表单(FormBorderStyle = none):

[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));
}

这是在Paint事件上设置自定义边框:

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

但请参阅此screenshot

内部表格矩形没有圆角。

如何使蓝色内部表格矩形也具有圆形边缘,所以它看起来不像截图?

2 个答案:

答案 0 :(得分:9)

地区专业只是切断角落。要拥有真正的圆角,您必须绘制圆角矩形。

Drawing rounded rectangles

绘制所需形状的图像并将其放在透明表格上可能更容易。更容易绘制但无法调整大小。

答案 1 :(得分:0)

请注意,您泄漏CreateRoundRectRgn()返回的句柄后,您应该在使用DeleteObject()后将其释放。

Region.FromHrgn()复制定义,因此它不会释放句柄。

[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);
}

(将添加为评论但声誉为ded)