使用低级键盘挂钩更改键盘字符 [英] Using a low-level keyboard hook to change keyboard characters

查看:89
本文介绍了使用低级键盘挂钩更改键盘字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建自定义键盘布局.首先,我想让用户按下一个键,让我的键盘挂钩拦截它,然后输出一个我选择的键.

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.

我找到了这个键盘挂钩代码,出于我的目的,我尝试对其进行一些修改: http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx

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

我希望它声明一个新的KBD结构对象,将键盘挂钩提供的KBD结构复制到其中,修改我对象的vkCode以使用其他字符,然后用修改后的版本覆盖提供的对象.希望这应该使所有内容保持相同,除了它写一个不同的字符.

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.

不幸的是,它不起作用.键入原始键盘字符. Visual Studio输出窗格还出现一个A first chance exception of type 'System.ArgumentException' occurred in MirrorBoard.exe错误.

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?

谢谢!

推荐答案

Marshal.PtrToStructure的第二个参数必须是不是结构的类,而KBDLLHOOKSTRUCT可能是结构.

The second parameter for Marshal.PtrToStructure must be a class not a struct and KBDLLHOOKSTRUCT is probably a struct.

相反,您应该像这样使用它:

Instead you should use it like this:

KBDLLHOOKSTRUCT replacementKey = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
replacementKey.vkCode = 90; // char 'Z'
Marshal.StructureToPtr(replacementKey, lParam, false);

这篇关于使用低级键盘挂钩更改键盘字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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