Visual Basic FAQ

Pure VB: Centering a Form or Dialog on the Screen
     
Posted:   Thursday December 26, 1996
Updated:   Monday December 26, 2011
     
Applies to:   VB2, VB3, VB4-16, VB4-32, VB5, VB6
     
 Prerequisites
None.

This code is probably the first thing a VB developer asks. And now, while VB5 and VB6 provide screen positions as startup properties, I still prefer this tried-and-true method. Sometimes the simplest things are the best to stick with.
 BAS Module Code
None.

 Form Code
Add the following to the form load:

Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright 1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Sub Form_Load()

    Me.Move (Screen.Width - Me.Width) \ 2, (Screen.Height - Me.Height) \ 2

End Sub

'Alternate Method
'When you have several forms to position in your app, 
'you can wrap the Move code into a bas module sub, 
'then call it from any form, passing the form name 
'to position.

'Private Sub Form_Load()
'
'    CentreForm Me
'
'End Sub


'in a bas module
'Private Sub CentreForm(frm as Form)
'
'    frm.Move (Screen.Width - frm.Width) \ 2, (Screen.Height - frm.Height) \ 2
'
'End Sub
 Comments
Often you will see the recommendation that to centre a form, you should set the form's left and top properties as in:

      Me.Left = Screen.Width / 2
      Me.Top = Screen.Height / 2

While this method is certainly not incorrect, its execution involves two commands, and, on a slower system or one without accelerated video, the user might see the form shift position first horizontally as the '.Left =' code is executed, then vertically as the '.Top =' code is executed.  The Move command performs both horizontal and vertical repositioning together in one move.


 
 

PayPal Link
Make payments with PayPal - it's fast, free and secure!

 
 
 
 

Copyright 1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy

 

Hit Counter