使用低级键盘钩子更改键盘字符
我正在创建自定义键盘布局。作为开始步骤,我想让用户按下一个键,让我的键盘钩子拦截它,并输出我选择的不同键。
我找到了这个键盘挂钩代码,我试图根据我的目的对其进行稍微修改: http://blogs.msdn.com/toub/archive/ 2006/05/03/589423.aspx
我已经将相关方法更改为:
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
KBDLLHOOKSTRUCT replacementKey = new KBDLLHOOKSTRUCT();
Marshal.PtrToStructure(lParam, replacementKey);
replacementKey.vkCode = 90; // char 'Z'
Marshal.StructureToPtr(replacementKey, lParam, true);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
我希望它声明一个新的KBD结构对象,将键盘钩子提供的KBD结构复制到其中,修改我的对象的vkCode使用不同的字符,然后用我的修改版本覆盖提供的对象。除了写出不同的字符之外,这应该会保持一切相同。
不幸的是,它不起作用。输入原始键盘字符。 Visual Studio 输出窗格还会出现A first opportunity exception of type 'System.ArgumentException' returned in MirrorBoard.exe
错误。
我可以在这里做什么来拦截键盘挂钩并将其替换为我选择的字符?
谢谢!
I'm creating a custom keyboard layout. As the beginning step, I want to have the user press a key, have my keyboard hook intercept it, and output a different key of my choosing.
I found this keyboard hook code, which I'm trying to slightly modify for my purposes:
http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx
I've changed the relevant method to this:
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
KBDLLHOOKSTRUCT replacementKey = new KBDLLHOOKSTRUCT();
Marshal.PtrToStructure(lParam, replacementKey);
replacementKey.vkCode = 90; // char 'Z'
Marshal.StructureToPtr(replacementKey, lParam, true);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
I want it to declare a new KBD structure object, copy the KBD structure supplied by the keyboard hook into it, modify my object's vkCode to use a different character, and then overwrite the supplied object with my modified version. This should hopefully keep everything the same except for the fact that it writes a different character.
Unfortunately, it's not working. The original keyboard character is typed. The Visual Studio output pane also gets a A first chance exception of type 'System.ArgumentException' occurred in MirrorBoard.exe
error.
What can I do here to intercept the keyboard hook and replace it with a character of my choosing?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Marshal.PtrToStructure 的第二个参数必须是类而不是结构,并且 KBDLLHOOKSTRUCT 可能是结构。
相反,你应该像这样使用它:
The second parameter for
Marshal.PtrToStructure
must be a class not a struct andKBDLLHOOKSTRUCT
is probably a struct.Instead you should use it like this: