【问题标题】:How to simulate combination of keys(such as shift+left for selecting text) using global keyboard hook and postmessage()?如何使用全局键盘钩子和 postmessage() 模拟键组合(例如 shift+left 用于选择文本)?
【发布时间】:2011-04-07 09:38:17
【问题描述】:

我正在使用全局键盘挂钩 (WH_KEYBOARD_LL) 并将键发送到浏览器句柄。我可以让用户按下一个键,但无法按下组合键(例如 shift+left 用于选择文本)。代码如下...

private IntPtr ProcessKey(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0
        && wParam == (IntPtr)WM_KEY_EVENT.WM_KEYDOWN
        || wParam == (IntPtr)WM_KEY_EVENT.WM_SYSKEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        int vkCode1 = Marshal.ReadInt32(wParam);//here I am getting runtime
        //error as Attempted to read or write protected memory.
        //This is often an indication that other memory is corrupt. 

        SafeNativeMethods.PostMessage(m_browserHandle,(uint)WM_KEY_EVENT.WM_KEYDOWN,  
            Convert.ToInt32((System.Windows.Forms.Keys)vkCode),
            Convert.ToInt32((System.Windows.Forms.Keys)vkCode1));
    }

    return SafeNativeMethods.CallNextHookEx(_hookID, nCode, wParam, lParam);
}

[DllImport("user32.dll", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);

public static class WM_KEY_EVENT
{
    public static int WM_KEYDOWN = 0x0100;
    public static int WM_SYSKEYDOWN = 0x0104;
    public static int WM_KEYUP=0x0101;
    public static int WM_SYSKEYUP=0x0105;
};

我读到了一些我们可以通过使用 wParam 获得按键组合的地方,这会产生错误,如上面的代码所示。请建议如何避免该错误或其他方法。

【问题讨论】:

标签: c# keyboard-hook


【解决方案1】:

您的代码中有一些错误。您将 wParam 视为指针(因为您使用它调用 ReadInt32),但根据 the documentation 它包含窗口消息。

lParam 你应该取消引用(使用 Marshal.PtrToStructure)到 KBDLLHOOKSTRUCT,它包含键代码和修饰键状态。

而且我看不出将 vkCode 转换为 System.Windows.Fórms.Keys 值,然后再次转换为 int 的意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多