Visual Basic FAQ

SetWindowPlacement: Activating a Window Without Focus
     
Posted:   Saturday December 28, 1996
Updated:   Monday December 26, 2011
     
Applies to:   VB4-32, VB5, VB6
     
 Prerequisites
None.

This code demonstrates loading and showing a form while keeping the focus on the main form.
 BAS Module Code
None.

 Form Code
Start a new project, and add two forms to it, using the default names. On Form1, place a Command button (Command1), and add the following:

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 Const SW_SHOWNORMAL = 1
Private Const SW_SHOWMINIMIZED = 2
Private Const SW_SHOWMAXIMIZED = 3
Private Const SW_SHOWNOACTIVATE = 4
Private Const SW_SHOW = 5

Private Type RECT
   Left    As Long
   Top     As Long
   Right   As Long
   Bottom  As Long
End Type

Private Type POINTAPI
   x       As Long
   y       As Long
End Type

Private Type WINDOWPLACEMENT
   length            As Long
   flags             As Long
   showCmd           As Long
   ptMinPosition     As POINTAPI
   ptMaxPosition     As POINTAPI
   rcNormalPosition  As RECT
End Type

Private Declare Function GetWindowPlacement Lib "user32" _
   (ByVal hwnd As Long, lpwndpl As WINDOWPLACEMENT) As Long

Private Declare Function SetWindowPlacement Lib "user32" _
   (ByVal hwnd As Long, lpwndpl As WINDOWPLACEMENT) As Long


Private Sub Command1_Click()

    Dim hWndToActivate As Long
    Dim currRect As RECT
    Dim currWinP As WINDOWPLACEMENT
  
    hWndToActivate = Form2.hwnd
  
    With currWinP
       .length = Len(currWinP)
       Call GetWindowPlacement(hWndToActivate, currWinP)

       .length = Len(currWinP)
       .flags = 0&
       .showCmd = SW_SHOWNOACTIVATE
    End With
    
    Call SetWindowPlacement(hWndToActivate, currWinP)
  
End Sub
 Comments
Run the project. Pressing the command button loads and shows Form2, however the focus remains on Form1.

 
 

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