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

时间:2016-08-03 10:05:25

标签: c++ windows multithreading hook

我试图安装一个在后台线程中运行的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()时发生错误

0 个答案:

没有答案
相关问题