Win32 hooks with MFC
This sample was contributed by Dror Kremer.
I've recently needed to use Win32 Hooks and it took me a couple of days until I got everything right. I've searched the net for a complete working sample of how to use it and couldn't find any sample (even in C, let alone MFC), so I dug out a sample from VC 2 that used hooks, and borrowed pieces of code from it.
To use the server simply do the following :
- Include HooksClient.h and .cpp in the project.
- Add CHooksClient to the list of classes your class (the one you want to process hook messages) derives from. (i.e. class CMySpyWnd : public CWnd, public CHooksClient or class CMySpyApp : public CWinApp, public CHooksClient).
- Derive the constructor of CHooksClient in the constructor(s) of the class.
- Add a function to the class : void ProcessHookMessage(HWND hwnd, UINT nMessage, WPARAM wParam, LPARAM lParam); This function will be called for each message sent or posted to the window. This function is declared as pure virtual in CHooksClient so you _must_ implement it.
To start spying on a window call InstallWindowHook(HWND hwnd) and pass the handle of the window you want to spy on, or call InstallSystemHook() to spy on all windows. When you call InstallWindowHook to spy on a window, you will actually get messages back on all windows in that thread, that's beacause windows can install a hook for a thread not a window.
NOTICE: When you call InstallSystemHook() and run the program in the debugger, it may cause MSDEV to crash (or even the whole system) the reason for this is that when you install a system-wide hook, you monitor MSDEV as well, and when it tries to break, and "suspend" your program's execution it can't because the hooks server continues to send messages about stuff that's happening in MSDEV - that's my guess anyway, because I have no way of debugging this besides installing a debugging hook and I don't wanna :)
BTW: Copy the hooks dll to the debug or release directory of the test program (or anywhere in the path) otherwise it won't work.
Download Files The zip file is 37K.