NoName
NoName

Reputation: 8025

How to properly set global mouse hook on background thread?

I write a code that hook Low Level Mouse in background thread. How I properly set HOOKPROC m_Callback so it is called in same that thread? Thank!

std::mutex m;
std::condition_variable cv;
bool tk_worker_kill = false;

LRESULT CALLBACK m_Callback(int nCode, WPARAM wparam, LPARAM lparam)
{
    // do something
    return CallNextHookEx(_m_hook, nCode, wparam, lparam);
}

// this function is called by a background thread
void set_Hook()
{
    std::unique_lock<std::mutex> lk(m);
    _m_hook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)m_Callback, NULL, 0);

    cv.wait(lk, []{return tk_worker_kill; });
    lk.unlock();
}


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
    std::thread worker(set_Hook);
}

Upvotes: 0

Views: 420

Answers (1)

Richard Critten
Richard Critten

Reputation: 2145

You need a message loop in your background thread:

This hook is called in the context of the thread that installed it. The call is made by sending a message to the thread that installed the hook. Therefore, the thread that installed the hook must have a message loop.

Source: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644986(v=vs.85).aspx

Upvotes: 2

Related Questions