简体   繁体   English

使用全局挂钩更改键盘事件不起作用

[英]Changing keyboard events with global hook doesn't work

I am trying to make a little program that installs a global hook and catches keyboard input. 我正在尝试制作一个安装全局钩子并捕获键盘输入的小程序。 For now, I am trying to make every input changed to 'X' for example. 目前,我正在尝试将每个输入更改为“ X”。 So if i write anywhere "hello" it will actually write "XXXXX". 因此,如果我在任何地方写“ hello”,它将实际上写为“ XXXXX”。 I succeeded with hooking and even stopping any input from passing my hook but I can't figure out how to change the input. 我成功进行了挂钩,甚至阻止了任何输入通过挂钩,但是我不知道如何更改输入。

The relevant method: 相关方法:

IntPtr HookCallBack(int nCode, IntPtr wParam, IntPtr lParam)
{
        // Trying to change the input.
        Marshal.WriteInt32(lParam, 88);

        // Locked down
        if (isKeyboardLockedDown)
            return new IntPtr(1); // A non-zero return value blocks additional processing of key strokes.
        // Not locked down.
        else
            return NativeMethods.CallNextHookEx(hookId, nCode, wParam, lParam);
 }

As written above - if I understand right - lParam is the address where the input key is stored. 如上所述-如果我理解正确-lParam是输入键的存储地址。 Therefor I overwrite it with "X". 因此,我用“ X”覆盖它。 That method doesn't work for some reason. 出于某种原因,该方法不起作用。 Any suggestions? 有什么建议么?

If the input is X: 如果输入是X:

Invoke CallNextHookEx() 调用CallNextHookEx()

Otherwise 除此以外

Do not invoke CallNextHookEx(). 不要调用CallNextHookEx()。 Instead, call SendInput to post an X. 而是,调用SendInput发布X。

SendInput 发送输入

Synthesizes keystrokes, mouse motions, and button clicks. 合成击键,鼠标动作和按钮单击。

Note: In general it is unwise not to invoke CallNextHookEx(). 注意:通常,不调用CallNextHookEx()是不明智的。 Then again, it is in general not wise to replace all input with X :-) 再说一次,用X代替所有输入通常是不明智的:-)

iv'e done a similar project in C. Instead of changing the data i generated input. iv'在C中完成了类似的项目。无需更改数据即可生成输入。 It works smoothly and not slowing the typing process down. 它工作流畅,并且不会减慢键入过程的速度。 I used a global flag. 我使用了全局标志。 True for input i generate and false for input from the user. 我生成的输入为True,用户输入的为false。 This is pretty much how it looked: 这几乎是它的外观:

HookProc(int nCode, WPARAM wParam, LPARAM lParam) 
{  
    if(flag){ 
        flag = FALSE; 
        return CallNextHookEx(NULL, nCode, wParam, lParam);}  
    else{ 
        flag = TRUE; 
        keybd_event(what ever you want); 
        return 0;} 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM