02-18-2004, 02:15 PM | #1 (permalink) |
Crazy
Location: Raleigh, NC
|
[c++] windows keyboard hooks
Can someone give me a basic description of how to make a simple keyboard hook? I have looked in the msdn library and am still unclear about how to implement the SetWindowsHookEx() function.
Thanks
__________________
"Good artists copy, great artists steal." - Pablo Picasso Last edited by Digilogic; 02-18-2004 at 02:31 PM.. |
02-23-2004, 08:28 PM | #4 (permalink) |
Junkie
Location: San Francisco
|
I've screwed around with it trying to inject code into another process on Windows 9x (on NT you can just use VirtualAllocEx and CreateRemoteThread but the latter isn't implemented on 9x), but I couldn't get it working and stopped bothering because I figure everyone should be using 2000 or XP by now anyway. ;-) It is kind of confusing and I'm not sure why I couldn't do it before but some code I just wrote seems to work.
Basically you need a LRESULT CALLBACK HookProc(int, WPARAM, LPARAM), called by Windows when the thread(s) you are monitoring get whatever type of message, and then you have to call SetWindowsHookEx with a pointer to that function, the handle to the DLL the function is in if necessary, the type of hook, and which threads. If you want the hook on another process you have to put the callback function in a DLL. First the driver program, as simple as it gets: Code:
#include <windows.h> extern "C" void startKeyMonitoring(); extern "C" void stopKeyMonitoring(); int main() { startKeyMonitoring(); Sleep(10000); stopKeyMonitoring(); return 0; } Code:
#include <windows.h> #include <sstream> BOOL __stdcall DllMain(HANDLE, DWORD, LPVOID) { return TRUE; } HHOOK g_hhk; extern "C" __declspec(dllexport) void startKeyMonitoring() { HMODULE hLib = LoadLibrary("hooklib.dll"); HOOKPROC proc = (HOOKPROC)GetProcAddress(hLib, "KeyProc"); g_hhk = SetWindowsHookEx(WH_KEYBOARD, proc, hLib, 0); } extern "C" __declspec(dllexport) void stopKeyMonitoring() { UnhookWindowsHookEx(g_hhk); } extern "C" __declspec(dllexport) LRESULT CALLBACK KeyProc(int nCode, WPARAM wParam, LPARAM lParam) { std::ostringstream oss; oss << "Here I am in process " << GetCurrentProcessId() << " with a message for you."; MessageBox(NULL, oss.str().c_str(), "Hello", MB_OK); return CallNextHookEx(g_hhk, nCode, wParam, lParam); } Last edited by n0nsensical; 02-23-2004 at 08:32 PM.. |
Tags |
hooks, keyboard, windows |
|
|