• Welcome to Valhalla Legends Archive.
 

(VB-Intermediate) Function to Center a Window

Started by Grok, March 10, 2003, 04:32 AM

Previous topic - Next topic

Grok

Some of you beginners or intermediates (or someone new to using WIN32 API from VB) might find this mildly interesting.

The function centers the normalized window state, given that window's handle.  It need not be your own window.  In fact, it's quite easy to move your own windows using their form object.  This function is more useful to center another process' window.

Public Function CenterWindow(ByVal hWnd As Long) As Long
    
    Dim wp As WINDOWPLACEMENT
    Dim lret As Long
    Dim pX As Long, pY As Long
    Dim cX As Long, cY As Long
    Dim pSW As Long, pSH As Long
    
    CenterWindow = False
    If hWnd = 0 Then Exit Function                  'make sure we have handle
    lret = GetWindowPlacement(hWnd, wp)
    If lret = 1 Then
        pSW = Screen.Width \ Screen.TwipsPerPixelX
        pSH = Screen.Height \ Screen.TwipsPerPixelY
        cX = wp.rcNormalPosition.Right - wp.rcNormalPosition.Left + 1
        cY = wp.rcNormalPosition.Bottom - wp.rcNormalPosition.Top + 1
        pX = (pSW - cX) \ 2
        pY = (pSH - cY) \ 2
        lret = SetWindowPos(hWnd, HWND_NOTOPMOST, pX, pY, cX, cY, SWP_SHOWWINDOW)
        If lret = 1 Then
            CenterWindow = 0
            Exit Function
        End If
    End If
    CenterWindow = GetLastError
    
End Function

HTH someone.