简体   繁体   English

如何使用全局键盘钩子和postmessage()模拟键的组合(例如shift + left用于选择文本)?

[英]How to simulate combination of keys(such as shift+left for selecting text) using global keyboard hook and postmessage()?

I am using a global keyboard hook (WH_KEYBOARD_LL) and sending the keys to a browser handle. 我正在使用全局键盘挂钩(WH_KEYBOARD_LL),并将键发送到浏览器句柄。 I am able to get a single key pressed by the user but not able to get the combination of keys pressed(such as shift+left for selecting text).The code goes below... 我可以让用户按下一个键,但是不能按下组合键(例如,Shift +向左键选择文本)。代码如下...

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

I read some where that we can get the combination of key press by using wParam, which gives error as shown in the code above. 我读了一些我们可以使用wParam获得按键组合的地方,该错误给出了上面代码中所示的错误。 Please suggest how to avoid that error or some alternative way to do it. 请提出如何避免该错误或其他替代方法。

Your code has some errors in it. 您的代码中有一些错误。 You're treating wParam as a pointer (since you're calling ReadInt32 with it), but according to the documentation it contains the window message. 您正在将wParam视为指针(因为您正在使用它调用ReadInt32),但是根据文档,它包含窗口消息。

lParam you should derefernece (using Marshal.PtrToStructure) to a KBDLLHOOKSTRUCT , it contains the key code and modifier key state. lParam应该取消引用(使用Marshal.PtrToStructure)到KBDLLHOOKSTRUCT ,它包含键代码和修饰键状态。

And I don't see the point in casting vkCode to a System.Windows.Fórms.Keys value, and then right back to an int again. 而且我看不到将vkCode强制转换为System.Windows.Fórms.Keys值,然后再次重新转换为int的意义。

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

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