如何在后台线程上正确设置全局鼠标挂钩?
How to properly set global mouse hook on background thread?
我写了一段代码,在后台线程中挂钩低级鼠标。我如何正确设置 HOOKPROC m_Callback
以便在同一个线程中调用它?谢谢!
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);
}
您的后台线程中需要一个消息循环:
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.
来源:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644986(v=vs.85).aspx
我写了一段代码,在后台线程中挂钩低级鼠标。我如何正确设置 HOOKPROC m_Callback
以便在同一个线程中调用它?谢谢!
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);
}
您的后台线程中需要一个消息循环:
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.
来源: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644986(v=vs.85).aspx