First Time Trying to use Hooks

The code from my dll. Named newfile.dll. Compiled as:

gcc -c newfile.c
gcc -shared -o newfile.dll newfile.o


The file:

#include <windows.h>
#include <stdio.h>
#ifndef NEWFILE_H
#define NEWFILE_H

#ifdef __cplusplus
extern "C" {
#endif

__declspec(dllexport) void __stdcall MyFirstHook(){
printf("It works!");
}


#ifdef __cplusplus
}
#endif

#endif /* NEWFILE_H */



The main program:

#include <windows.h>

int main() {
HOOKPROC hkprcSysMsg;
HINSTANCE hinstDLL;
HHOOK hhookSysMsg;

hinstDLL = LoadLibrary(TEXT("newfile.dll"));
hkprcSysMsg = (HOOKPROC)GetProcAddress(hinstDLL, "MyFirstHook");

hhookSysMsg = SetWindowsHookEx(WH_KEYBOARD, hkprcSysMsg, hinstDLL,0);


return (EXIT_SUCCESS);
}


I'm trying to hook the keyboard and every time I press a key print out "it works!". I know I probably won't get much help, but anything is appreciated.
You are trying to make a Keylogger yeh?
That is the end goal but really right now I'm just trying to learn.
closed account (13bSLyTq)
Hi,

In your given program there are multiple problems such as you forgetting, the message loop and more importantly forgot the essential part of this program - hook callback, however I have created an example code for you:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<Windows.h>
#include <stdio.h>

HHOOK hHock = NULL;

LRESULT CALLBACK MyLowLevelHookCallback ( int nCode , WPARAM wParam , LPARAM lParam) // Hook callback
{
    printf("Key press\n");
    return CallNextHookEx(hHock , nCode ,wParam , lParam); //Finished with our hook call-back, so lets move to next one. 
}

int main() //Entry point
{
    MSG msg;
    hHock = SetWindowsHookEx(WH_KEYBOARD_LL , MyLowLevelHookCallback , NULL,NULL); //Install global Keyboard hook

    while(!GetMessage(&msg, NULL, NULL, NULL)) { // Message Loop
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    UnhookWindowsHookEx(hHock); // uninstall global keyboard hook before exiting 
	return 0;
} 


Hope this helped,
OrionMaster
Last edited on
Topic archived. No new replies allowed.