using System.Drawing;using System.Windows.Forms;2. 创建自定义窗体类public class RoundedForm : Form{ [Dll">

c#怎么设计窗口圆角

来源:这里教程网 时间:2026-02-21 16:48:13 作者:

如何在 C# 中设计窗口圆角

在 C# 中,可以通过以下步骤设计窗口圆角:

1. 引入 WinForms 库

<code class="csharp">using System.Drawing;
using System.Windows.Forms;</code>

2. 创建自定义窗体类

<code class="csharp">public class RoundedForm : Form
{
    [DllImport("Gdi32.dll")]
    private static extern bool RoundRect(IntPtr hWnd, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);
    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        // 窗口半径
        int radius = 20;
        // 确定窗口圆角区域
        Region region = new Region();
        GraphicsPath path = new GraphicsPath();
        path.AddRoundRect(new Rectangle(0, 0, Size.Width, Size.Height), radius, radius);
        region.RegionPath = path;
        // 将圆角区域应用到窗口
        Region = region;
    }
}</code>

3. 使用自定义窗体类创建窗口

<code class="csharp">RoundedForm form = new RoundedForm();
form.Text = "窗口圆角示例";
form.Size = new Size(400, 400);
form.ShowDialog();</code>

解释:

DllImport("Gdi32.dll"):导入 GDI32 DLL 中的 RoundRect 函数,该函数用于绘制圆角矩形。 OnResize():当窗口大小更改时,该重写方法会自动调用,并使用 GraphicsPath 和 Region 创建一个圆角区域。 RegionPath:将 GraphicsPath 设置为 Region 的 Path,从而将圆角区域应用到窗口。

通过以上步骤,你可以在 C# 中创建具有圆角的窗口。

相关推荐