SetWindowsHookEx与WH_KEYBOARD不适用于我,我错了什么? [英] SetWindowsHookEx with WH_KEYBOARD doesn't work for me, what do I wrong?

查看:888
本文介绍了SetWindowsHookEx与WH_KEYBOARD不适用于我,我错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

}

在控制台上打印消息并创建一个文件,但什么也没有发生。我错了什么?

This code on every key press while the loop is going should print message on console and create a file, but nothing is happening. What do I wrong ?

推荐答案

我会引用其他主题


控制台窗口完全由CSRSS处理,这是一个系统
进程。将钩子安装到进程中意味着将DLL
注入它。由于CSRSS是如此重要(它对运行
系统至关重要,并且代码在运行时作为LocalSystem,它是本地
超级管理员用户),你不允许注入代码。所以你
不能钩住它的任何窗口。

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.

在你的简单控制台中没有真正的窗口消息应用程序,所以你的钩子不必被调用,在你的情况下,你甚至不是注入你的钩子,而是使用线程模式钩子。根据MSDN文档,当消息即将被处理时被调用:

There are no real window messages taking place in your simple console application, so your hook does not have to be called, and in your case you are not even injecting your hook but using thread mode hook only. Per MSDN documentation it is called when messages are about to be processed:


应用程序定义或库定义的回调函数与
SetWindowsHookEx函数。当
应用程序调用GetMessage或PeekMessage函数并且
是要处理的键盘消息(WM_KEYUP或WM_KEYDOWN)时,系统调用此函数。

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.

现在让我告诉你你可以做什么来开始接收你的钩子上的电话:

Now let me show you what you can do to start receiving calls on your hook:

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);
//}

Do MessageBox 然后关闭它开始输入 - 你将开始获取hook调用。

Do MessageBox and before closing it start typing - you will start getting hook calls.

这篇关于SetWindowsHookEx与WH_KEYBOARD不适用于我,我错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆