Prasenjit Maity
Prasenjit Maity

Reputation: 69

Windows button Round corner in c#

I'm using visual Studio 2015. I want to Create a rounded corner windows button in C#. Like this: RoundedButton I'm musing this code

[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`.

When I use this on Form_paint, it is working fine, but not working on Button.

Upvotes: 3

Views: 4344

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

The problem is that you are still getting the size for the rounded region from the whole form, rather than the button, and then you are applying the region to the form as well, rather than to the button. So, in essence, by putting the region-manipulating code in the button's Paint event, you have changed when it's happening, but you haven't changed what it's doing. Try this:

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

Upvotes: 3

Related Questions