How to create a User Control with rounded corners?

If you want really round corner and not only transparent trick you can use this example:

private int radius = 20;
[DefaultValue(20)]
public int Radius
{
    get { return radius; }
    set
    {
        radius = value;
        this.RecreateRegion();
    }
}

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect,
    int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);

private GraphicsPath GetRoundRectagle(Rectangle bounds, int radius)
{
    float r = radius;
    GraphicsPath path = new GraphicsPath();
    path.StartFigure();
    path.AddArc(bounds.Left, bounds.Top, r, r, 180, 90);
    path.AddArc(bounds.Right - r, bounds.Top, r, r, 270, 90);
    path.AddArc(bounds.Right - r, bounds.Bottom - r, r, r, 0, 90);
    path.AddArc(bounds.Left, bounds.Bottom - r, r, r, 90, 90);
    path.CloseFigure();
    return path;
}

private void RecreateRegion()
{
    var bounds = ClientRectangle;

    //using (var path = GetRoundRectagle(bounds, this.Radius))
    //    this.Region = new Region(path);

    //Better round rectangle
    this.Region = Region.FromHrgn(CreateRoundRectRgn(bounds.Left, bounds.Top,
        bounds.Right, bounds.Bottom, Radius, radius));
    this.Invalidate();
}

protected override void OnSizeChanged(EventArgs e)
{
    base.OnSizeChanged(e);
    this.RecreateRegion();
}

Region with GraphicsPath:

enter image description here

Region with Windows API:

enter image description here

The difference between this approach and making transparent:

  • Setting round region, the control has really round corners and you can see what is behind the round part despite when it is transparent, you will see background of form.
  • Setting round region, when you click on removed rounded part, click pass through the region and reaches behind, but if you use transparency trick click on transparent region will handle by the control.

You can use any of these 2 options. Making transparent or setting region based on your requirement.

Download

You can download the code or clone the repository here:

Leave a Comment