c# - Windows 按钮 C# 中的圆角

标签 c# winforms button rectangles rounded-corners

我正在使用 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 上不起作用。

最佳答案

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

关于c# - Windows 按钮 C# 中的圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51456369/

相关文章:

c# - 将 Kinect v1 代码与 Kinect v2 重用

c# - 使用 MVVM 模式(特别是使用 MVVM Light),如何实现不仅仅是基元的模型?

javascript - 类型错误 : Cannot read property 'publish' of undefined in (ReactJS)

wpf - 在 WPF : how to disable the animation when the button after be pressed? 中

java - Android 按钮 onClick 不起作用

c# - 当轮廓可以撕裂时,如何检测简单形状(使用emgu cv)?

c# - 如何在此处应用 C# 中的 "template"或 "skeleton"代码?

c# - 如何以编程方式检测 Windows 桌面应用程序中是否启用/禁用了 javascript? (网络浏览器控件)

c# - 相同分辨率下不同电脑上的字体大小不同

c# - 在 OpenFileDialog 中过滤文件的正则表达式