【问题标题】:How do I create 2 rounded corners in winforms with borders?如何在带边框的winforms中创建2个圆角?
【发布时间】:2019-05-15 17:47:38
【问题描述】:

我有一个代码可以帮助我制作一个无边框的圆角WinForm。它工作正常,但问题是它没有边框,所以我想给它添加圆角边框。另外,我只希望 TopLeftBottomRight 圆角。

这是我当前的代码:

public partial class mainForm : Form
{
    [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();
    this.FormBorderStyle = FormBorderStyle.None;
    Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
}

WPF 中很容易实现,但我如何在WinForms 中获得它?

我该怎么办?

【问题讨论】:

  • 代码好像和this question一样。您可以使用ControlPaint 手动绘制边框。还是你想成为able to resize无边框形式?
  • 是的,是一样的。另外,我现在还没有考虑调整大小,但是是的,边框是我唯一想要的。除此之外,我希望能够只有两个圆角。
  • CreateRoundRectRgn() 不会只给你两个圆角。请改用 .NET Region(GraphicsPath) 构造函数。而且您不能真正忽略窗口自行调整大小的可能性,因此这至少需要在 Load 事件中完成,可能在 Resize 事件中完成。

标签: c# .net winforms


【解决方案1】:

您可以在客户区手动绘制边框。这很简单,但您必须注意为子控件布局留出一些边距。

尽管如此,这仍然是一个挑战,因为只有Graphics.FillRegion,没有办法绘制轮廓或DrawRegion方法。

我们可以创建GraphicsPath 并用Graphics.DrawPath 绘制它,但是创建它很棘手,例如this implementation 与使用 CreateRoundRectRgn() 方法创建的不匹配。

因此,有 2 个区域的技巧:具有边框颜色的较大区域和具有客户端颜色的内部较小区域。这将留下一点外部区域,这将在视觉上创建一个边框。

readonly Region _client;

public Form1()
{
    InitializeComponent();
    // calculate smaller inner region using same method
    _client = Region.FromHrgn(CreateRoundRectRgn(1, 1, Width - 1, Height - 1, 20, 20));
    Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
}

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    // FillRectangle is faster than FillRegion for drawing outer bigger region
    // and it's actually not needed, you can simply set form BackColor to wanted border color
    // e.Graphics.FillRectangle(Brushes.Red, ClientRectangle);
    e.Graphics.FillRegion(Brushes.White, _client);
}

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 2014-11-25
    • 2016-08-17
    • 2021-06-17
    • 2023-03-30
    相关资源
    最近更新 更多