How to Trap VB Form Lost Focus with GetActiveWindow APIID: Q69792
|
The LostFocus event in Microsoft Visual Basic is useful when transferring control within an application, and you can use the form deactivate and activate events in versions 2.0 and 3.0 to see if the entire form has lost the focus. However, in version 1.0, no global routine exists to check for the entire form losing the focus. To check whether your version 1.0 application has lost the focus, periodically check the Windows API function GetActiveWindow in a Visual Basic timer event, as explained below.
The only way that version 1.0 provides a check for loss of focus on a
form or control is by triggering the LostFocus event. A form does
support a LostFocus event; however, a form will only get focus if
there are no controls on that form. Focus goes to the controls on a
form, and when you click any other visible form, the control's
LostFocus procedure will be called. A control's LostFocus procedure
will also be called when another control on the form is activated. To
perform a routine that occurs only when the form loses focus requires
careful management of what generated a LostFocus event on each control
(such as setting a flag if another control's Click event was called).
For a simpler method to check if a whole form has lost the focus, you
can call the Windows API function GetActiveWindow, located in USER.EXE
(a DLL provided with Windows 3.0). The GetActiveWindow API call
returns the window handle of the currently active window, which is the
new window that you last clicked anywhere in Microsoft Windows. In a
timer event procedure for the form, call GetActiveWindow and compare
the handle of the currently active Window with the handle of the form
window (Form1.hWND). If the handle differs, you know the form has lost
the focus. The following program example demonstrates this technique:
Declare Function GetActiveWindow Lib "User" () As Integer
Dim FOCUS As Integer
Const TRUE = -1
Const FALSE = 0
Sub Timer1_Timer ()
If FOCUS = TRUE Then
' Compare the handle of the currently active Window with the handle
' of the Form1 window:
If GetActiveWindow() <> Form1.hWND Then
'Do form's lost-focus routines here.
Print "Lost Focus"
FOCUS = FALSE
End If
End If
End Sub
Sub Command1_Click ()
FOCUS = TRUE
End Sub
Sub Form_Click ()
FOCUS = TRUE
Timer1.Interval = 10
End Sub
"Programming Windows: the Microsoft Guide to Writing Applications for
Windows 3," Charles Petzold. Microsoft Press, 1990.
"Microsoft Windows Software Development Kit: Reference Volume 1,"
version 3.0.
WINSDK.HLP file shipped with Microsoft Windows 3.0 Software
Development Kit.
Additional query words: 2.00 3.00
Keywords :
Version :
Platform :
Issue type :
Last Reviewed: June 8, 1999