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

Resizing Controls When Resizing Form

0.00/5 (No votes)
1 Jun 2013 3  
Making the sizes of the controls change automatically when resizing the form.

Introduction

One of the problems that faces the programmers is the screen resolution and the sizes of the controls. Making the software changes screen resolution or obliges the user to do so are both annoying. Furthermore, the user may prefer sizes different of the ones chosen by the developer. Properties such as Anchor and Docking could be useful, but don't let the sizes of the controls preserve their initial ratios. 

The Code 

The following code allows the user to resize the form to any desired value while at the same time resizing the controls with the same ratio.  

Option Strict On

Public Class Form1

    Dim CW As Integer = Me.Width ' Current Width
    Dim CH As Integer = Me.Height ' Current Height
    Dim IW As Integer = Me.Width ' Initial Width
    Dim IH As Integer = Me.Height ' Initial Height

    Private Sub Form1_Resize(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Me.Resize

        Dim RW As Double = (Me.Width - CW) / CW ' Ratio change of width
        Dim RH As Double = (Me.Height - CH) / CH ' Ratio change of height

        For Each Ctrl As Control In Controls
            Ctrl.Width += CInt(Ctrl.Width * RW)
            Ctrl.Height += CInt(Ctrl.Height * RH)
            Ctrl.Left += CInt(Ctrl.Left * RW)
            Ctrl.Top += CInt(Ctrl.Top * RH)
        Next

        CW = Me.Width
        CH = Me.Height

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles MyBase.Load

        IW = Me.Width
        IH = Me.Height

    End Sub

End Class

Now, try to add some controls on the form, and then run the program. Try to resize the form to any value (you can even maximize it), and see how the controls are resized accordingly. 

See the attached example.

Please  note that the attached example is not a well designed application; it is just a simple example that clarifies the technique.

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