【问题标题】:Windows button Round corner in c#c#中的Windows按钮圆角
【发布时间】:2018-12-29 13:58:10
【问题描述】:

我正在使用 Visual Studio 2015。我想在 C# 中创建一个圆角窗口按钮。像这样: RoundedButton 我正在思考这段代码

[System.Runtime.InteropServices.DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern System.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
);

[System.Runtime.InteropServices.DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
private static extern bool DeleteObject(System.IntPtr hObject);

private void button1_Paint(object sender, PaintEventArgs e)
{
    System.IntPtr ptr = CreateRoundRectRgn(0, 0, this.Width, this.Height, 15, 15); // _BoarderRaduis can be adjusted to your needs, try 15 to start.
    this.Region = System.Drawing.Region.FromHrgn(ptr);
    DeleteObject(ptr);
}
When I use this on `Form_paint`, it is working fine, but not working on `Button`.

当我在Form_paint 上使用它时,它可以正常工作,但不能在Button 上工作。

【问题讨论】:

  • 您正在设置this.Region,这是表单的区域,而不是设置button1.Region,除非这只是您的示例中的拼写错误。
  • 感谢您宝贵的时间和知识。在此代码上更正 button1.Region 后,我仅在此按钮的左上角得到结果。请分享一些关于它的东西。
  • 您还根据表单的大小而不是按钮的大小来设置区域的大小。
  • 非常感谢......System.IntPtr ptr = CreateRoundRectRgn(0, 0, button1.Width, button1.Height, 15, 15); button1.Region = System.Drawing.Region.FromHrgn(ptr);它工作正常。

标签: c# winforms button rectangles rounded-corners


【解决方案1】:

问题是您仍然从整个表单而不是按钮获取圆角区域的大小,然后您将该区域也应用于表单,而不是按钮。因此,从本质上讲,通过将区域操作代码放入按钮的 Paint 事件中,您已经更改了 when 它发生的时间,但您并没有改变 what 它正在执行的操作.试试这个:

[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern System.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
);

[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
private static extern bool DeleteObject(System.IntPtr hObject);

private void button1_Paint(object sender, PaintEventArgs e)
{
    IntPtr ptr = CreateRoundRectRgn(0, 0, button1.Width, button1.Height, 15, 15); 
    button1.Region = Region.FromHrgn(ptr);
    DeleteObject(ptr);
}

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 2013-10-01
    • 1970-01-01
    • 2019-05-17
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多