Tip 49: Centering Forms
Created: April 10, 1995
Abstract
To make your Visual Basic® applications more visually attractive, you can center each form on your screen. Centering forms can be done by using the Height and Width properties of the form and then using the Move method to position the form at its new location on the screen.
Centering a Form on the Screen
To center a Visual Basic® form on the screen at run time is very simple. The Screen object can tell you the width and height of a specific form, the Height property reports the height of a form or control, and the Width property reports the width of a form or control.
If you subtract the form's height from the screen's height and divide the result by 2, you can center the form vertically on the screen. Likewise, subtracting the form's width from the screen's width and dividing the result by 2 gives you the position needed to center the form vertically on the screen. It is then a simple matter of executing the Move method to actually center the form on the display screen.
Example Program
The following program shows how you can center a form in your Visual Basic application.
Create a new project in Visual Basic. Form1 is created by default.
Add the following code to the Form_Load event for Form1:
Sub Form_Load()
Dim TopCorner As Integer
Dim LeftCorner As Integer
If Form1.WindowState <> 0 Then Exit Sub
TopCorner = (Screen.Height - Form1.Height) \ 2
LeftCorner = (Screen.Width - Form1.Width) \ 2
Form1.Move LeftCorner, TopCorner
End Sub
|