Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Fun with padding and border painting

So you want to build a professional looking UI with Visual Studio 2005… NET 2.0 has made a big move forward in enabling developers to create a rich and customizable user interfaces. Many controls have been improved or completely rewritten, but some remained with the same look and feel. In this article, I’ll try to follow a common scenario and build a very very simple UI, featuring a SplitContainer, a TreeView, TextBox and a RichTextBox.
We’ll begin with new Windows Application and add two SplitContainers to the Form. The left-side panel with contain a TreeView, while the right-side panel will host another SplitContainer, hosting a multiline TextBox in the top, and a RichTextBox in a bottom panel.
The first layout would look like this:

Shown in a Document Outline Window:

We can see that RichTextBox has that old 3D border, while the other two controls paint accordingly to selected XP color scheme. Also, all controls are pushing into form’s border; we’d like to add some space on the inside, so our controls could breath and stand out more.

First, let’s get rid of that 3D Border (BorderStyle = None). Then, add some padding around the controls:

splitContainer1.Panel1.Padding = new System.Windows.Forms.Padding(4, 4, 0, 4);
splitContainer1.Panel2.Padding = new System.Windows.Forms.Padding(0, 4, 4, 4);

The form now looks like this:

Better… To add a border around RichTextBox, we’ll add additional, one-pixel padding to the panel that hosts RichTextBox:

splitContainer2.Panel2.Padding = new System.Windows.Forms.Padding(1);

Finally, let’s do some custom border painting:

private void splitContainer2_Panel2_Paint(object sender, PaintEventArgs e)
{
   Rectangle rectangle = richTextBox1.DisplayRectangle;
   rectangle.Offset(splitContainer2.Panel2.Padding.Left,
   splitContainer2.Panel2.Padding.Top);
   using (Pen pen = new Pen(System.Windows.Forms.
VisualStyles.VisualStyleInformation.TextControlBorder, 2))
   {
       e.Graphics.DrawRectangle(pen, rectangle);
   }
}

And if grey just isn’t your color, do this:

public Form1()
{
   InitializeComponent();
   splitContainer1.BackColor = ProfessionalColors.ToolStripContentPanelGradientEnd;
}

That's it. Simple, isn't it?

Default Blue Color Scheme:

Silver Color Scheme:

Olive Green Color Scheme: