How-To... - Centering a form on screen - a better way

When someone loads your program, you would always like it to appear in the centre of the users screen. To achieve this effect, you can use the following code in the Form_Load sub:-

Private Sub Form_Load()
Me.Move (Screen.Width - Me.Width) \ 2, (Screen.Height - Me.Height) \ 2
End Sub

The above code will work most of the time, but not always. Say, for example, the user loads your program up and the form centres on the screen. The user then moves the current form up to the top of the screen. Then, clicks a button or menu which shows another form, and hides the current one. The user closes the second form, and then the first form shows, but not in the centre. Why?

The reason for this is that the form will only centre on the screen when it is loaded not shown. To make sure that the form always centres on the screen, use the following code in the Form_Activate sub:-

Private Sub Form_Activate()
Me.Move (Screen.Width - Me.Width) \ 2, (Screen.Height - Me.Height) \ 2
End Sub

Now, your form will always be on the centre of the screen when showing or loading the form.

-----------

Tip supplied by Richard James(killiesoft@hotmail.com)


This site is Copyright © 1999 of David Cowan. VB How-To, Dodgesoft and DodgeSoft Productions is Copyright © 1999 of David Cowan. Source-code and programs are copyright of their respective owners. For a messageboard, click here