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 above another form
DescriptionThis example shows how to center a form above another form in Visual Basic.
Keywordscenter form
CategoriesControls, Software Engineering
 
Subroutine CenterFormOnForm calls function GetScreenWorkingArea to get the screen's area excluding the task bar. It then calculates the position of the new form to center it above the lower form. It adjusts the position if necessary to keep the upper form on the screen.
 
Public Sub CenterFormOnForm(ByVal frm_above As Form, ByVal _
    frm_below As Form)
Dim working_area As RECT
Dim x As Single
Dim y As Single

    ' Get the working area.
    working_area = GetScreenWorkingArea(frm_below)

    ' Position the upper form.
    x = frm_below.Left + (frm_below.Width - _
        frm_above.Width) / 2
    If x < working_area.Left Then x = working_area.Left
    If x + frm_above.Width > working_area.Right Then
        x = working_area.Right - frm_above.Width
    End If

    y = frm_below.Top + (frm_below.Height - _
        frm_above.Height) / 2
    If y < working_area.Top Then y = working_area.Top
    If y + frm_above.Height > working_area.Bottom Then
        y = working_area.Bottom - frm_above.Height
    End If

    frm_above.Move x, y
End Sub
 
Function GetScreenWorkingArea uses the SystemParametersInfo API function to get the screen's working area. If it succeeds, it converts the result into twips. If it fails, the routine uses the screen's entire area.
 
' Return the screen's working area.
Public Function GetScreenWorkingArea(ByVal frm As Form) As _
    RECT
Dim working_area As RECT

    If SystemParametersInfo(SPI_GETWORKAREA, _
        0, working_area, 0) <> 0 _
    Then
        ' Convert into twips.
        working_area.Left = frm.ScaleX(working_area.Left, _
            vbPixels, vbTwips)
        working_area.Right = frm.ScaleX(working_area.Right, _
            vbPixels, vbTwips)
        working_area.Top = frm.ScaleX(working_area.Top, _
            vbPixels, vbTwips)
        working_area.Bottom = _
            frm.ScaleX(working_area.Bottom, vbPixels, _
            vbTwips)
    Else
        ' We did not get the work area bounds.
        ' Use the entire screen.
        working_area.Left = 0
        working_area.Right = Screen.Width
        working_area.Top = 0
        working_area.Bottom = Screen.Height
    End If

    GetScreenWorkingArea = working_area
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated