I try to call SetWindowsHookEx function to install a hook. Everything works right expect when I call SetWindowsHookEx I get an unresolved external error. When I call the functions in my DLL without SetWindowsHookEx everything works fine(so it’s not a linking/include error). I import my DLL using a DEF file. I’m using Visual Studio 2022.
The exact error: unresolved external symbol __imp_SetWindowsHookExW referenced in function main
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <TestLibrary.h>
int main()
{
printf("Loading library\n");
HMODULE libHandle = LoadLibraryA("TestLibrary");
if (libHandle == NULL) printf("***ERROR*** loading library\n");
printf("Getting address of hook procedure\n");
HOOKPROC procAddress = (HOOKPROC)GetProcAddress(libHandle, "KeyboardProc");
if (procAddress == NULL) printf("***ERROR*** getting address\n");
printf("Installing hook\n");
HHOOK hook = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)procAddress, libHandle, 0);
if (hook == NULL) printf("ERROR installing hook\n");
}
>Solution :
SetWindowsHookEx is a WIN32 function implemented in User32 dll.
Since you are statically linking with it, you need to add an import to a lib file.
Add this under your includes section:
#pragma comment( lib, "user32" )