vlastachu
vlastachu

Reputation: 257

dll hook function not called

I trying to catch and retranslate keyboard and mouse events. So I use SetWindowsHookEx and function in dll. First time Ш have one big error - GetProcAddress can't get my function. That answer help me a lot GetProcAddress returns NULL

Now i can call functions from dll and I can see effect from hook: my keyboard not work while programm is run. But hook not called.

main.cpp

#include <Windows.h>
#include <WinUser.h>
#include <iostream>
#include <fstream>
using namespace std;
HHOOK hhk;


int main(){
    HINSTANCE hinstLib = LoadLibrary(TEXT("hookdll.dll")); 
    typedef void (*Install)();
    typedef void (*Uninstall)();
    typedef LRESULT (_stdcall *HookProcedure)(int, WPARAM , LPARAM );
    Install install = (Install) GetProcAddress(hinstLib, "install");
    Uninstall uninstall = (Uninstall) GetProcAddress(hinstLib, "uninstall");
    HookProcedure hookProc = (HookProcedure) GetProcAddress(hinstLib, "_hookProcedure@12");//omg
    cout << GetLastError()<< "\n";
    install();
    hhk = SetWindowsHookEx(WH_KEYBOARD, hookProc, hinstLib, NULL);
    cout << GetLastError()<< "\n";
    for(int i = 0; i < 50; i++){
        Sleep(200);
        cout << i << "\n";
    }
    UnhookWindowsHookEx(hhk);
    uninstall();
    return 0;
}

hookdll.cpp

#include <Windows.h>
#include <iostream>
#include <fstream>

HINSTANCE hinst;
HHOOK hhk;
std::ofstream myfile;

extern "C" __declspec(dllexport)
LRESULT CALLBACK hookProcedure(int code, WPARAM w, LPARAM l)
{
    MessageBox(NULL, (LPCWSTR)L"HEY HEY", (LPCWSTR)L"Test", MB_OK);
    //never saw this message
    return CallNextHookEx(NULL, code, w, l);
}

extern "C" __declspec(dllexport) void install() { 
    myfile.open("log.txt",std::ios_base::app);
    myfile << "\ninstall " << GetLastError();
}
extern "C" __declspec(dllexport) void uninstall() {
    myfile << "\nuninstall " << GetLastError();
    myfile.close();
}

extern "C" __declspec(dllexport)
BOOL WINAPI DllMain(  __in  HINSTANCE hinstDLL, __in  DWORD fdwReason, __in  LPVOID lpvReserved) {
    hinst = hinstDLL;
    return TRUE;
}

Upvotes: 2

Views: 1319

Answers (1)

Captain Obvlious
Captain Obvlious

Reputation: 20063

The keyboard hook allows you to intercept WM_KEYDOWN and WM_KEYUP window messages. Console applications do not receive these messages unless there is an active windows message queue. If you want to see and process these messages in a console application create a window and give it keyboard focus. Make sure you do message pumping with the GetMessage and DispatchMessage WinAPI calls in the thread that owns the window.

If you do not want to create a window you can use WH_KEYBOARD_LL to intercept keyboard related messages sent to the active message queue of a thread. You will still need to use GetMessage to read from the queue or it will eventually start dropping messages.

Upvotes: 1

Related Questions