c++winapicreatewindowex

I want to receive messages on a thread other than the ui thread


I'm trying to create a function that detects software signals within a game. However, my thread is a separate thread from the UI thread and should not affect the UI thread.

I've tested it by creating a message-only window and calling getmessage on my thread, I receive messages fine until I click on a game, but when I click on a game, all messages are not received.

My test code is below.

mythread.cpp

    HINSTANCE instance = GetModuleHandle(nullptr);

    WNDCLASSEX wndclass;
    wndclass.cbSize = sizeof(WNDCLASSEX);
    wndclass.lpfnWndProc = myproc;
    wndclass.hInstance = instance;
    wndclass.lpszClassName = "test";

    DWORD ret = RegisterClassEx(&wndclass);
    HWND hwnd = CreateWindowEx(0, "test", "dummy", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, instance, 0);

    RAWINPUTDEVICE device = { 0 };

    devices.usUsagePage = 1;
    devices.usUsage = 2;
    devices.dwFlags = RIDEV_INPUTSINK;
    devices.hwndTarget = hwnd;

    RegisterRawInputDevices(devices, 1, sizeof(RAWINPUTDEVICE));

    MSG msg;
    while(true)
    {
        while (GetMessage(&msg, hwnd, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }

myproc

LRESULT CALLBACK myproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    switch (msg)
    {
        case WM_INPUT:
        {
            ...
        }
    }
    return DefWindowProc(hwnd, msg, wparam, lparam);
}

Can you please let me know what I did wrong?


Solution

  • You cannot do that, all your window message processing has to be on the thread that created the window. You can pass messages from other threads (or processes) to it using PostMessage, but not the other way around.

    I'm not really sure why you want to receive your messages on another thread anyway, it sounds like what you're looking for is the producer-consumer pattern, where your gui thread is producing events into a collection of some kind (a vector synchronized using a critical section that triggers an event wait handle, for example), and your other thread consumes them as they come.