我试图安装一个在后台线程中运行的Windows挂钩,直到用户通过调用cancelRun()
停止它。
但是,在installHook()
之后调用cancelRun()
时,我已经调用了#34;#34;"异常。
部首:
#pragma once
#include <iostream>
#include <thread>
#include <Windows.h>
#pragma comment(lib, "user32.lib")
class GestureEngine{
private:
static HHOOK hHook_;
std::thread thread_;
bool cancelRun_ = false;
public:
GestureEngine(){
}
static GestureEngine& instance();
static inline LRESULT CALLBACK mouseProc(const int nCode, const WPARAM wParam, const LPARAM lParam)
{
// ....
return CallNextHookEx(hHook_, nCode, wParam, lParam);
}
void threadproc();
void installHook();
void cancelRun();
};
代码:
#include "GestureEngine.h"
HHOOK GestureEngine::hHook_ = NULL;
GestureEngine& GestureEngine::instance(){
static GestureEngine s_instance;
return s_instance;
}
void GestureEngine::installHook(){
thread_ = std::thread(&GestureEngine::threadproc, this);
cancelRun_ = false;
}
void GestureEngine::cancelRun(){
if (cancelRun_ == false) {
cancelRun_ = true;
thread_.join();
thread_.detach();
UnhookWindowsHookEx(hHook_);
cancelRun_ = false;
}
}
void GestureEngine::threadproc(){
MSG msg;
hHook_= SetWindowsHookEx( WH_MOUSE_LL, mouseProc, NULL, NULL );
while(!cancelRun_){
GetMessage(&msg, NULL, 0, 0);
TranslateMessage(&msg);
DispatchMessage(&msg);
};
return;
}
执行thread_ = std::thread(&GestureEngine::threadproc, this);
方法
installHook()
时发生错误