'in a module
Option Explicit
Public Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Public Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Public Const GWL_WNDPROC As Long = -4
Public Const WM_USER As Long = &H400
Public Const WM_KEYDOWN As Long = &H100 'the specific message you wanted
Public Const CUSTOM As Long = WM_USER + 1 'this is just a sample of a custom message
Public lngOldProc As Long 'holds the address of the old window procedure
Public Sub Hook(ByVal hWnd As Long)
'save the old procedure address
lngOldProc = GetWindowLong(hWnd, GWL_WNDPROC)
'set the new procedure address
'CustomProc [b]must[/b] be located in a standard module, not an object module
SetWindowLong hWnd, GWL_WNDPROC, AddressOf CustomProc
End Sub
Public Sub UnHook(ByVal hWnd As Long)
'restore the old procedure
'this [b]must[/b] be done before the program terminates, or you'll crash VB
SetWindowLong hWnd, GWL_WNDPROC, lngOldProc
End Sub
Public Function CustomProc(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
'this is your custom message handler procedure
Select Case wMsg
Case WM_KEYDOWN
'got a keydown message, wParam is the virtual key
'you could have an "Exit Function" here if you didn't want to allow the system to act on this message (the same goes for all cases)
Case CUSTOM
'got the custom message (if it was ever sent)
Case Else
'not required, but if you got here, the procedure can't handle the message, so let the system do it
'you may also want to allow the system to process them all anyway, and you just want to see when certain messages are used
'in that case, stick the CallWindowProc call outside of the select case
CustomProc = CallWindowProc(lngOldProc, hWnd, wMsg, wParam, lParam)
End Select
End Function
'now with all of that out the way, something like this would be in your form
'[b] do not press the IDE stop button. use the X of the form to close[/b]
Private Sub Form_Load()
Hook Me.hWnd 'begin the subclassing
End Sub
Private Sub Form_Unload(Cancel As Integer)
UnHook Me.hWnd 'end the subclassing
End Sub