Windows按钮C#中的圆角

时间:2018-07-21 13:03:03

标签: c# winforms button rectangles rounded-corners

我正在使用Visual Studio2015。我想在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上工作。

1 个答案:

答案 0 :(得分:1)

问题在于,您仍然从整个表单而不是按钮中获取舍入区域的大小,然后将区域也应用到表单中,而不是按钮中。因此,从本质上讲,通过将区域操作代码置于按钮的Paint事件中,您已经更改了发生时间,但是您没有更改什么它在做。试试这个:

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