To catch any messages sent to a form by windows, you need to tell Windows what procedure to send the message to. You do this using the SetWindowLong api call. Use the following code to start catching your messages:
Module Code
'// variable that stores the previous message handler
Public ProcOld As Long
Public Const GWL_WNDPROC = (-4)
'// Windows API Call for catching messages
Public Declare Function SetWindowLong Lib "user32" Alias
"SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As
Long) As Long
'// Windows API call for calling window procedures
Public 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
Public Function WindowProc(ByVal hWnd As Long, ByVal iMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long) As Long
'// ----WARNING----
'// do not attempt to debug this procedure!!
'// ----WARNING----
'// this is our implementation of the message handling routine
'// determine which message was recieved
Select Case iMsg
Case else
'// Ignore all messages for the moment
End Select
'// pass all messages on to VB and then return the value to windows
WindowProc = CallWindowProc(procOld, hWnd, iMsg, wParam, lParam)
End Function
Form Code
'// form_load event. Catch all those messages!
Private Sub Form_Load()
On Error Resume Next
'// saves the previous window message handler. Always restore this
value
'// AddressOf command sends the address of the WindowProc procedure
'// to windows
ProcOld = SetWindowLong(hWnd, GWL_WNDPROC, AddressOf WindowProc)
End Sub
'// form_queryunload event. Return control to windows/vb
Private Sub Form_Unload(Cancel As Integer)
'// give message processing control back to VB
'// if you don'//t do this you WILL crash!!!
Call SetWindowLong(hWnd, GWL_WNDPROC, procOld)
End Sub
Basically, when the Form loads, the SetWindowLong API is called. This tells windows to send any messages to the WindowProc procedure in the module, rather than the procedure VB uses. This API returns a handle to the old procedure... we need to save this so that we can restore it when our program ends. If we don't, everything will crash! Now, all messages for the specified hWnd (which was passed when we called SetWindowLong) will be sent to WindowProc. Please note that there will be a lot of messages (ie thousands)... this is why you cannot debug the WindowProc procedure... the VB debugging tools cannot cope with this quantity of messages being sent, even when the program is paused. Instead, you need to turn of Background Compile (Tools|Options|General). This should catch most errors before your program is run. If it doesn't, VB will crash when an error occurs... you need to be very careful!
Comments