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:
' REQUIRES THE MSGHOOK.DLL COMPONENT' you can omit the following constant, because it is' defined in the MsgHook type libraryConst WM_ACTIVATEAPP = &H1CDim WithEvents FormHook As MsgHookPrivate Sub Form_Load() ' subclass the form with events Set FormHook = New MsgHook FormHook.StartSubclass hWndEnd SubPrivate 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 Else ' The application is being deactivated End If End IfEnd Sub