Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB5,VB6
Expertise: Intermediate
Jan 1, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Detect when the application gets or loses the input focus

VB forms exposes the Activate and Deactivate events, which fire when the form gets and loses the focus because the user has clicked on another form of the same application. However, VB doesn't fire any event when the user clicks on a form that belongs to another Windows application. In some cases this can be a problem, because your program might rely on that that has been gathered when the form has been loaded - for example, the list of files in a given directory - and you can't be 100% sure that the data hasn't been modified by the user (for example, by deleting the files from Explorer).

To get a notification when the application as a whole gets or loses the input focus, you must subclass a form in your application, and watch for the WM_ACTIVATEAPP message. When this message is received, the wParam argument holds zero if the application is losing the focus, or a non-zero value if the application is getting the input focus. This is the code that does the trick:


' you can omit the following constant, because it is
' defined in the MsgHook type library

Dim WithEvents FormHook As MsgHook

Private Sub Form_Load()
    ' subclass the form with events
    Set FormHook = New MsgHook
    FormHook.StartSubclass hWnd
End Sub

Private Sub FormHook_AfterMessage(ByVal uMsg As Long, ByVal wParam As Long, _
    ByVal lParam As Long, retValue As Long)
    If uMsg = WM_ACTIVATEAPP Then
        If wParam Then
            ' The application is being activated
            ' The application is being deactivated
        End If
    End If
End Sub
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date