C#: Programmatically Centering a Control (Extension Method)


I have recently been working on ensuring that one of our Windows Forms applications renders correctly under all DPI settings. One of the things I needed to do was center a control in its parent container at runtime. I came up with the following three extension methods that are available to anything that extends the System.Windows.Forms.Control class. The following code will center the control based upon its parent control. Thus if the control is placed directly on the form, it will be centered in the form. On the other hand if the control is inside a GroupBox or similar container, the control will be centered relative to the bounds of the container.

public static class Positioning
{
    /// <summary>
    /// Centers the control both horizontially and vertically 
    /// according to the parent control that contains it.
    /// </summary>
    /// <param name="control"></param>
    public static void Center(this Control control)
    {
        control.CenterHorizontally();
        control.CenterVertically();
    }

    /// <summary>
    /// Centers the control horizontially according 
    /// to the parent control that contains it.
    /// </summary>
    public static void CenterHorizontally(this Control control)
    {
        Rectangle parentRect = control.Parent.ClientRectangle;
        control.Left = (parentRect.Width - control.Width) / 2;
    }

    /// <summary>
    /// Centers the control vertically according 
    /// to the parent control that contains it.
    /// </summary>
    public static void CenterVertically(this Control control)
    {
        Rectangle parentRect = control.Parent.ClientRectangle;
        control.Top = (parentRect.Height - control.Height) / 2;
    }
}

// Usage
// -----
// private void Form1_Load(object sender, EventArgs e)
// {
//     this.button1.CenterVertically();
//     this.button1.CenterHorizontally();
//     this.button1.Center();
// }
Advertisements

6 Responses to “C#: Programmatically Centering a Control (Extension Method)”

  1. Francesco Pretto Says:

    I like it. 2 little improvements:
    1) Center() function should calculate the control.Location Point and set it. This will ensure there is only one invalidation for the control;
    2) A safeguard in case of null control.Parent. I just return in this case.

    • Nick Olsen Says:

      Good points. Thanks for the input.

  2. Nick Says:

    Thanks! I used this in my vb.net app for work. Worked like a charm. Favorited!

  3. thewinstonsmithRob Says:

    Great methods thanks!!

  4. Iwet Says:

    Why have I Error?-‘System.Windows.Forms.Control’ does not contain a definition for ‘CenterHorizontally’ and no extension method ‘CenterHorizontally’ accepting a first argument of type ‘System.Windows.Forms.Control’ could be found (are you missing a using directive or an assembly reference?)

  5. Nick Gandy Says:

    Supports multiple controls

    Public Shared Sub CenterInParentVertically(ParamArray ctls() As Control)

    If ctls.Count > 0 Then

    Dim height = ctls.Max(Function(o) o.Bottom) – ctls.Min(Function(o) o.Top)
    Dim topControl = ctls.OrderBy(Function(o) o.Top).First
    Dim difference = ((topControl.Parent.ClientRectangle.Height – height) / 2) – topControl.Top

    For Each ctl In ctls
    ctl.Top += difference
    Next

    End If

    End Sub

    Public Shared Sub CenterInParentHorizontally(ParamArray ctls() As Control)

    If ctls.Count > 0 Then

    Dim width = ctls.Max(Function(o) o.Right) – ctls.Min(Function(o) o.Left)
    Dim topControl = ctls.OrderBy(Function(o) o.Left).First
    Dim difference = ((topControl.Parent.ClientRectangle.Width – width) / 2) – topControl.Left

    For Each ctl In ctls
    ctl.Left += difference
    Next

    End If

    End Sub

    Public Shared Sub CenterInParent(ParamArray ctls() As Control)

    CenterInParentHorizontally(ctls)
    CenterInParentVertically(ctls)

    End Sub


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: