我编写了一个在后台线程中挂钩低级鼠标的代码。我如何正确设置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);
}
答案 0 :(得分:2)
您需要在后台线程中使用消息循环:
在安装它的线程的上下文中调用此钩子。 通过向安装了该安装的线程发送消息来进行调用 钩。因此,安装钩子的线程必须有一个 消息循环。
来源: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644986(v=vs.85).aspx