logo
vbRad Home
Source Code
Book Reviews
Forum
Links
About Us
Contribute

Compare Databases with SQL Effects Clarity
 
 How to detect when the application loses and receives focus

Posted on
2/18/2001
Author:
Robert Gelb
Email:
Not Shown
Applies To OS:
All
Product:
5, 6



Unfortunately, in VB the forms don't include an event when the application loses and receives focus. The good news that you can still get it. The bad news is that the solution relies on AddressOf operator and subclassing. The form receives a message that it lost focus, VB just doesn't expose it. The message to catch is WM_ACTIVATEAPP. Then the complimentary parameter in the message wParam indicates whether the app has gained or lost focus.

Warning, never end programs that use AddressOf operator by pressing the End button on the VB toolbar. End the program by clicking the X (close) button on the form.

Add the following to a .BAS module

Option Explicit

Private Declare Function CallWindowProc Lib "user32" Alias _
	"CallWindowProcA" (ByVal lpPrevWndFunc As Long, _
	ByVal hwnd As Long, ByVal Msg As Long, _
	ByVal wParam As Long, ByVal lParam As Long) As Long 
 
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" _
	(ByVal hwnd As Long, ByVal nIndex As Long, _
	ByVal dwNewLong As Long) As Long 

Private Const WM_ACTIVATEAPP = &H1C
Private Const GWL_WNDPROC =    -4
Public lpPrevWndProc As Long
Public gHW As Long 

Public Sub Hook()

	'Establish a hook to capture messages to this window
	lpPrevWndProc = SetWindowLong(gHW, GWL_WNDPROC, AddressOf WindowProc) 

End Sub

Public Sub Unhook()

	Dim temp As Long
	
	'Reset the message handler for this window
	temp = SetWindowLong(gHW, GWL_WNDPROC, lpPrevWndProc)
	
End Sub

Function WindowProc(ByVal hw As Long, ByVal uMsg As Long, _
	ByVal wParam As Long, ByVal lParam As Long) As Long

	'Check for the ActivateApp message
	If uMsg = WM_ACTIVATEAPP Then
		'Check to see if Activating the application
		If wParam = 0 Then	'Application Received Focus
			Form1.Caption = "Focus Restored"
		Else
			'Application Lost Focus
			Form1.Caption = "Focus Lost"
		End If
	End If 
	
	'Pass message on to the original window message handler
	WindowProc =  CallWindowProc(lpPrevWndProc, hw, uMsg, wParam, lParam) 
End Function

Add the following code to the form

Option Explicit

Sub Form_Load()

    gHW = Me.hwnd   'Store handle to this form's window
    Hook    'Call procedure to begin capturing messages for this window
    
End Sub
Private Sub Form_Unload(Cancel As Integer)

    'Call procedure to stop intercepting the messages for this window
    Unhook
    
End Sub

Add Your Comment  

Name: Email Address: all fields optional
Notify me via email when someone responds to this message (valid email required).

Enter the word: