Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCenter a form taking the taskbar into account
Keywordscenter form, taskbar
CategoriesTips and Tricks
 
Use the SystemParametersInfo API function to get the bounds of the work area (the screen area excluding the task bar). Convert the results from pixels into twips and use these values to center the form.
 
Private Type RECT
    Left As Long
    Top As Long
    Right As Long
    Bottom As Long
End Type
Private Declare Function SystemParametersInfo Lib "user32" _
    Alias "SystemParametersInfoA" (ByVal uAction As Long, _
    ByVal uParam As Long, ByRef lpvParam As RECT, ByVal _
    fuWinIni As Long) As Long
Private Const SPI_GETWORKAREA = 48

' Center the form taking the task bar into account.
Private Sub CenterForm(ByVal frm As Form)
Dim wa_info As RECT
Dim wa_wid As Single
Dim wa_hgt As Single
Dim wa_left As Single
Dim wa_top As Single

    If SystemParametersInfo(SPI_GETWORKAREA, _
        0, wa_info, 0) <> 0 _
    Then
        ' We got the work area bounds.
        ' Center the form in the work area.
        wa_wid = ScaleX(wa_info.Right, vbPixels, vbTwips)
        wa_hgt = ScaleY(wa_info.Bottom, vbPixels, vbTwips)
        wa_left = ScaleX(wa_info.Left, vbPixels, vbTwips)
        wa_top = ScaleY(wa_info.Top, vbPixels, vbTwips)
    Else
        ' We did not get the work area bounds.
        ' Center the form on the whole screen.
        wa_wid = Screen.Width
        wa_hgt = Screen.Height
    End If

    ' Center the form.
    frm.Move (wa_wid - Width + wa_left) / 2, _
             (wa_hgt - Height + wa_top) / 2
End Sub

' Center the form.
Private Sub Form_Load()
    ' Make the form really big so it's easy to see that it
    ' is centered.
    Width = Screen.Width - 1440
    Height = Screen.Height - 1440

    ' Center the form.
    CenterForm Me
End Sub
 
Chris Tryon points out:

Would it not be easier to just add the sysinfo tool to the form. Then you could use sysinfo.workspaceheight, width and so on. This will take into account not only the taskbar, but the MS Office shortcut bar (if it is docked).

Good point. The program will probably be a little smaller without the control, but the added convenience is certainly worth it, particularly if you're users are likely to have the Office shortcut bar running.

Note, however, that I have been told this control seems to ignore the task bar in Windows 2000. Your mileage may vary.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated