C# Programming > Windows Forms

C# Align User Interface

C# User Interface

The user interface of a C# application is an important part of a program. A user-friendly interface keeps things organized. Having buttons and textboxes all over the place makes the C# program look messy and unprofessional.

As some of you may know, Visual Studio has a menu named Format which gives several commands to align different controls. This isn't C# code by the way, this is still in the design-time of the application.

The tools under the Format menu are excellent and they really make it simple to create a beautiful, clean user interface in C#.Net. But what happens when you have dynamic elements in the user interface? Say for example, that a Label changes its text at run-time but you want to keep it centered in the Form.

In order to use the same tools from the Format menu, we are going to have to write the equivalent funcitonality in C# code, so it can be called programmatically at run-time. Programmatically aligning user controls allows programmers to create a dynamic user interface in C#.

Align User-Interface C# Functions

The functions themselves will not be very difficult or complex. They just have to be well organized and in this case, be static functions to make it possible to call them in C# without having to intialize a class.

So for example, here's a code-snippet from the Align C# class:

public class UI
{
     public static class CenterInForm
     {
          public static void Horizontally(Form parentForm, Control control)
          {
              Rectangle surfaceRect = parentForm.ClientRectangle;
              control.Left = (surfaceRect.Width / 2) - (control.Width / 2);
          }

          public static void Vertically(Form parentForm, Control control)
          {
               Rectangle surfaceRect = parentForm.ClientRectangle;
               control.Top = (surfaceRect.Height / 2) - (control.Height / 2);
          }
     }
}

Notice that the funcitons have a lot of room for improvement. Centering does not have to be limited to a parent Form, it can be applied to any other container, such as a GroupBox or a Panel.

Download the full source code down below to get the rest of the aligning user-interface functions. They all work based on two user interface elements, but you could easily modify it to work with an array of .NET controls instead. Used correctly you can design a dynamic user interface in C# that stays neat and organized...

Back to C# Article List