Windows按钮c#中的圆角



我使用的是visual Studio 2015。我想在C#中创建一个圆角窗口按钮。像这样:圆形按钮我在思考这个代码

[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上不工作。

问题是,您仍然从整个表单而不是按钮中获取圆角区域的大小,然后您也将该区域应用于表单,而不是按钮。因此,从本质上讲,通过将区域操作代码放在按钮的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);
}

最新更新