gpt4 book ai didi

c++ - 带有 WH_KEYBOARD 的 SetWindowsHookEx 对我不起作用,我错了什么?

转载 作者:可可西里 更新时间:2023-11-01 14:41:27 26 4
gpt4 key购买 nike

#include <iostream>
#include <fstream>
#define _WIN32_WINNT 0x501
#include <windows.h>

using namespace std;

HHOOK hKeyboardHook = 0;
LRESULT CALLBACK KeyboardCallback(int code,WPARAM wParam,LPARAM lParam) {
cout << "a key was pressed" << endl;
ofstream myfile;
myfile.open ("hookcheck.txt", ios::ate | ios::app);
myfile << "a key was pressed\n";
myfile.close();
return CallNextHookEx(hKeyboardHook,code,wParam,lParam);
}

int main() {

HWND consoleWindow = GetConsoleWindow();
HINSTANCE hInstCons = (HINSTANCE)GetWindowLong( consoleWindow, GWL_HINSTANCE );
hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD, (HOOKPROC)KeyboardCallback, (HINSTANCE)consoleWindow, GetCurrentThreadId());

MessageBox(NULL, "It is keyboard time!", "Let's Go", MB_OK);

}

循环进行时每次按键时的这段代码应该在控制台上打印消息并创建一个文件,但什么也没有发生。我做错了什么?

最佳答案

我会引用 another topic :

Console windows are handled entirely by CSRSS, which is a system process. Installing a hook into a process means injecting your DLL into it. Since CSRSS is so important (it's vital for running of the system, and code within runs as LocalSystem, which is the local super-admin user), you're not allowed to inject code into it. So you can't hook any of its windows.

在您的简单控制台应用程序中没有真正的窗口消息发生,因此您的 Hook 不必被调用,在您的情况下您甚至没有注入(inject)您的 Hook ,而只是使用线程模式 Hook 。根据 MSDN 文档,当消息即将被处理时调用它:

An application-defined or library-defined callback function used with the SetWindowsHookEx function. The system calls this function whenever an application calls the GetMessage or PeekMessage function and there is a keyboard message (WM_KEYUP or WM_KEYDOWN) to be processed.

现在让我向您展示如何开始接听挂机电话:

MessageBox(NULL, _T("It is keyboard time!"), _T("Let's Go"), MB_OK);

//for(int i=0; i<=10; i++) {
// cout << i << endl;
// Sleep(1000);
//}

执行 MessageBox 并在关闭它之前开始输入 - 您将开始收到钩子(Hook)调用。

关于c++ - 带有 WH_KEYBOARD 的 SetWindowsHookEx 对我不起作用,我错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11176408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com