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

12

我正在使用以下代码使我的窗体(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);

看看这个 截图.

内部表单矩形没有圆角。

我该如何使蓝色的内部表单矩形也有圆角,这样它就不会像屏幕截图一样了?

2个回答

9

Region属性只是简单地切掉了角落。要获得真正的圆角,您需要绘制圆角矩形。

绘制圆角矩形

更容易的方法是绘制所需形状的图像并将其放在透明表单上。虽然更容易绘制,但无法调整大小。


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

(想作为评论添加,但声望已经减少了)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接