Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Draw a Border Around Any C# Winform Control

0.00/5 (No votes)
9 Jan 2016 1  
Trick to draw a border of any color and width around any winform control

Introduction

Many times, we need to add/change the border of a WinForm control. In WPF, it's very easy and flexible to do so. But in Winforms, it might be tricky sometimes.

Background

Most of the Winform controls have a property BorderStyle that allows for a border to be shown around that control. But the look and feel of that border cannot be changed. And there are controls (button, groupbox, etc.) that do not have this property. So, there is no direct way of adding a Border around these controls.

Show Me the Code!

OK, enough talk! The following magic lines allow us to add a border around a control:

public class MyGroupBox : GroupBox
{
   protected override void OnPaint(PaintEventArgs e)
   {
     base.OnPaint(e);
     ControlPaint.DrawBorder(e.Graphics, ClientRectangle,
                                  Color.Black, BORDER_SIZE, ButtonBorderStyle.Inset,
                                  Color.Black, BORDER_SIZE, ButtonBorderStyle.Inset,
                                  Color.Black, BORDER_SIZE, ButtonBorderStyle.Inset,
                                  Color.Black, BORDER_SIZE, ButtonBorderStyle.Inset);
   } 
}

The ControlPaint class allows to add a border around a control. The above call can be invoked in a Paint event handler of a control. The ControlPaint class has many other useful methods (along with an overload of DrawBorder) that you can explore to learn more!

Happy coding!!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here