Friday, July 18, 2008

SetWindowsHookEx Example

Here is an example of using SetWindowsHookEx.

First create a dll project with this cpp file

#include <windows.h>
#include <iostream>
#include <stdio.h>

HINSTANCE hinst;
HHOOK hhk;


LRESULT CALLBACK wireKeyboardProc(int code,WPARAM wParam,LPARAM lParam) {
FILE * fileLog = fopen("C:\\sknl.txt", "a+");
fprintf(fileLog,"OK");
CallNextHookEx(hhk,code,wParam,lParam);
fclose(fileLog);
return 0;
}

extern "C" __declspec(dllexport) void install() {
hhk = SetWindowsHookEx(WH_KEYBOARD, wireKeyboardProc, hinst, NULL);
}
extern "C" __declspec(dllexport) void uninstall() {
UnhookWindowsHookEx(hhk);
}

BOOL WINAPI DllMain( __in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved
) {

hinst = hinstDLL;
return TRUE;
}


This method has a
* dllmain which simply records the HINSTANCE
* has an install and uninstall method
* defines the keyboardProc call back method

Now in another process ( this is important and is needed as SetWindowsHook will only work if your callback is in a dll and not in your own process) you simply loadlibrary and install.


int _tmain(int argc, _TCHAR* argv[])
{

HINSTANCE hinst = LoadLibrary(_T("KeyboardLogger2.dll"));
if (hinst == NULL)
{
printf("null hinst");
}
typedef void (*Install)();
typedef void (*Uninstall)();

Install install = (Install) GetProcAddress(hinst, "install");
Uninstall uninstall = (Uninstall) GetProcAddress(hinst, "uninstall");


install();
int foo;
std::cin >> foo;

uninstall();
return 0;

}

3 comments:

Anonymous said...

I've tried this myself, no cigar.

Anonymous said...

I would like to use it but it keeps crashing without logging any key. Anybody's got any ideas?

Anonymous said...

You should add
extern "C"
and
__declspec(dllexport)
into DllMain()