Valhalla Legends Forums Archive | General Programming | (VB-Intermediate) Function to Center a Window

AuthorMessageTime
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.

[code]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[/code]

HTH someone.
March 10, 2003, 10:32 AM

Search