带有WH_KEYBOARD的SetWindowsHookEx卡在循环/队列中

SetWindowsHookEx with WH_KEYBOARD stuck in a loop/queue

本文关键字:循环 队列 SetWindowsHookEx WH KEYBOARD 带有      更新时间:2023-10-16

我正在尝试用dll注入挂接记事本。在exe运行并挂接记事本(我可以成功地告诉你)并且按下一些键之后,似乎发生了按键卡在循环或队列中(记事本没有响应)。exe解除挂起后,记事本会做出响应,所有按下的键都会显示在文本字段中。

exe

#include <iostream>
#include <fstream>
#include <windows.h>
#include <stdio.h>
HHOOK       hHook     = NULL;
HWND        handle    = NULL;
HMODULE     dll       = NULL;
HOOKPROC    address   = NULL;
DWORD       thread_id = 0;
using namespace std;
int main(){
    handle=FindWindow(NULL,L"Untitled - Notepad");
    if(handle==NULL){
        cout<<"Window not found"<<endl;
        getchar();
        return 0;
    }
    thread_id=GetWindowThreadProcessId(handle,NULL);
    if(thread_id==0){
        cout<<"ID not found"<<endl;
        getchar();
        return 0;
    }
    dll = LoadLibrary(TEXT("X:\qt\hook\debug\hook.dll"));
    if(dll==NULL){
        cout<<"hook.dll not found"<<endl;
        getchar();
        return 0;
    }
    address=(HOOKPROC)GetProcAddress(dll,"CallWndProc@12");
    if(address==NULL){
        cout<<"Address not found"<<endl;
        getchar();
        return 0;
    }
    hHook=SetWindowsHookEx(WH_KEYBOARD,address,dll,thread_id);
    if(hHook==NULL){
        cout<<"hook was not set"<<endl;
        return 0;
    }
    cout<<"Program successfully hooked"<<endl;
    cout<<"Press enter to unhook the function and stop the program"<<endl;
    getchar();
    UnhookWindowsHookEx(hHook);
    return 0;
}

dll

#include "hook.h"
#include <windows.h>
#include <iostream>
#include <fstream>
using namespace std;
extern "C"{
    __declspec(dllexport) LRESULT CALLBACK CallWndProc(int nCode,WPARAM wParam,LPARAM lParam){
        if(nCode<0){
           return CallNextHookEx(NULL,nCode,wParam,lParam);
        }
        ofstream file;
        file.open("X:\qt\klog\debug\function.txt");
        file<<"Function keyboard_hook calledn";
        file.close();
        return CallNextHookEx(NULL,nCode,wParam,lParam);
    }
}
BOOL APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved){
    switch(Reason) {
    case DLL_PROCESS_ATTACH: break;
    case DLL_PROCESS_DETACH: break;
    case DLL_THREAD_ATTACH:  break;
    case DLL_THREAD_DETACH:  break;
    }
    return TRUE;
}

在SetWindowsHookEx和UnookWindowsHookEX之间添加消息循环修复了

while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
    TranslateMessage(&Msg);
    DispatchMessage(&Msg);
}