停止/启动后台线程中的窗口挂钩

Stopping/Starting windows hook in background thread

本文关键字:窗口 线程 启动 后台 停止      更新时间:2023-10-16

我正试图安装一个在后台线程中运行的windows挂钩,直到它被用户通过调用cancelRun()停止。

然而,当在cancelRun()之后调用installHook()时,我会得到一个"abort has called"异常。

标题:

#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;
}

installHook()方法中执行行thread_ = std::thread(&GestureEngine::threadproc, this);时发生错误

我看到函数'threadproc'是class GestureEngine的成员,也许你可以尝试将其设置为全局成员或静态函数。