This is the .NET version of the hooking code I wrote for the VB6 Codebank.
http://www.vbforums.com/showthread.php?t=322261
This code allows you to hook into (subclass) external programs to intercept their windows messages. This allows you to do things like monitor button presses and keyboard input as well as respond to new menu items you can add to other programs which you don't have the source code for.
There are two parts to the code: a VB class and a C++ dll. I've attached the class and the compiled dll, the C++ dll source is in the previous thread if you want it.
Here is a description of the class clsHook.vb
Methods
GetWindowHandle(Caption, ClassName) - returns a handle to a top-level window
GetChildHandle(Caption, ClassName, TopLevelHandle) - returns a handle to a child window
AddMessage(NewMessage, strMessage) - Adds a windows message to the list of messages we want to monitor
SetHook - Sets the hook into the external program.
RemoveHook - Removes the hook from the external program.
Properties
isHooked - Returns True if the hook is set.
TargethWnd - Sets or returns the handle of the target window that is to be hooked
Events
SentMessage(ByRef m As Message) - Sent messages arrive here
SentRETMessage(ByRef m As Message) - Sent messages after processing arrive here
PostedMessage(ByRef m As Message) - Posted messages arrive here
HookError(Number, LocalMsg, APIMsg) - Raised on certain non-fatal error conditions
UnHook() - Raised when the hook is removed
Example
Code:
Public Class Form1
'This Program hooks Notepad.exe and monitors WM_CHAR,
' WM_LBUTTONDOWN, WM_LBUTTONUP messages
Private WithEvents EditHook As New clsHook
Private Const WM_LBUTTONDOWN = &H201
Private Const WM_LBUTTONUP = &H202
Private Const WM_CHAR = &H102
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
'Set the hook
Dim hWndMain As Integer
Dim hwndEdit As Integer
'Get handle to notepad
hWndMain = EditHook.GetWindowHandle(vbNullString, "NotePad")
'Get handle to notepad's Edit window
hwndEdit = EditHook.GetChildHandle("", "Edit", hWndMain)
'Make that our target
EditHook.TargethWnd = hwndEdit
'Add the message(s) we want to look for
EditHook.AddMessage(WM_CHAR, "WM_CHAR")
EditHook.AddMessage(WM_LBUTTONDOWN, "WM_LBUTTONDOWN")
EditHook.AddMessage(WM_LBUTTONUP, "WM_LBUTTONUP")
'Set the hook
EditHook.SetHook()
End Sub
Private Sub EditHook_PostedMessage(ByRef m As System.Windows.Forms.Message) _
Handles EditHook.PostedMessage
'Here is where Posted messages will arrive
Dim myPoint As Int32
Select Case m.Msg
Case WM_CHAR
'wParam points to char code
TextBox1.Text &= EditHook.Messages(m.Msg) & ": " & Chr(CByte(m.WParam.ToInt32)) _
& vbCrLf
Case WM_LBUTTONUP, WM_LBUTTONDOWN
'lParam: x-lo word, y-hi word
myPoint = m.LParam.ToInt32
TextBox1.Text &= EditHook.Messages(m.Msg) & ": " & CStr(myPoint And &HFFFF) _
& " : " & CStr(myPoint \ &H10000) & vbCrLf
End Select
End Sub
End Class
Edit: Added source code for C++ dll