2021-12-03

Working with hooks (SetWindowsHookEX & WH_GETMESSAGE)

I'll start with a description of what exactly I need and why.

I am making an in-game interface in a library (dll), and I need the ability to both receive and delete messages (prevent the target process from receiving them), depending on different conditions in the code.

In addition to messages from the mouse and keyboard, I do not need anything else. For this, there are two ways. Find some kind of hook that will allow me to receive messages from both the mouse and the keyboard, or put two separate hooks on the mouse and keyboard, but there will be much more code than with one hook.

I decided to go the first way and put a WH_GETMESSAGE hook on the messages of the thread that created the window. However, my attempts to block the message were unsuccessful.

LRESULT CALLBACK messageHandler(int nCode, WPARAM wParam, LPARAM lParam)
{
    return -1; // This works fine with WH_MOUSE or WH_KEYBOARD, but for some reason, with the WH_GETMESSAGE hook, the process still receives a message
}
 
DWORD WINAPI messageDispatcher(LPVOID thread)
{
    hookHandle = SetWindowsHookEx(WH_GETMESSAGE, messageHandler, GetModuleHandle(nullptr), *reinterpret_cast<DWORD*>(thread));
 
    if (!hookHandle)
    {
        return GetLastError();
    }
 
    MSG message{};
 
    while (GetMessage(&message, 0, 0, 0) > 0)
    {
        TranslateMessage(&message);
        DispatchMessage(&message);
    }
 
    return 0;
}

I'm not sure if WH_GETMESSAGE is the right hook for me. Perhaps much more experienced programmers will tell me that it is better to do, for example, two hooks, WH_MOUSE and WH_KEYBOARD, rather than using WH_GETMESSAGE.

But if, nevertheless, using WH_GETMESSAGE is not a bad idea, then please help me to make it so that I can control the receipt of some messages by the process (do not allow them to be seen by the process).



from Recent Questions - Stack Overflow https://ift.tt/3pmGZcL
https://ift.tt/eA8V8J

No comments:

Post a Comment