简体   繁体   English

WPF发送Ctrl+Key事件

[英]WPF sending Ctrl plus Key event

I'm using the following code我正在使用以下代码

private void Send(Key key)
{
    if (Keyboard.PrimaryDevice != null)
    {
        if (Keyboard.PrimaryDevice.ActiveSource != null)
        {
            var e1 = new System.Windows.Input.KeyEventArgs(
                Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key)
            { RoutedEvent = Keyboard.KeyDownEvent };
            bool b = InputManager.Current.ProcessInput(e1);
        }
    }
}

to send a key pressed event remapping the actual key I pressed on the keyboard.发送一个按键事件,重新映射我在键盘上按下的实际按键。

For example here:例如这里:

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.PageDown)
    {
        e.Handled = true;
        Send(Key.Right);
    }

I'm remapping the page down into a right arrow.我正在将页面重新映射为向右箭头。

How can I send a Control plus the right arrow Ctrl + pressed together?如何发送 Control 和右箭头Ctrl + 一起按下?

Basically the answer is already here (feel free to close as duplicated question).基本上答案已经在这里(随意关闭重复的问题)。

Just notice that in my case I need the definitions请注意,在我的情况下,我需要定义

    public const int VK_LCONTROL = 0xA2; //Left CONTROL key
    public const int VK_RIGHT = 0x27; //Right Arrow

So I simply do所以我只是做

keybd_event(VK_LCONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_RIGHT, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_RIGHT, 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);

where keybd_event is defined in the linked answer ( using System.Runtime.InteropServices; etc...).其中keybd_event在链接的答案中定义( using System.Runtime.InteropServices;等...)。

Full source code in the public repo (commented the other alternative solution). 公共存储库中的完整源代码(评论了另一个替代解决方案)。

Or use ready github project for .Net, Windows Input Simulator或使用现成的 github 项目为 .Net、 Windows 输入模拟器

It also uses "user32.dll" functions by marshaling它还通过编组使用“user32.dll”函数

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.PageDown)
    {
        e.Handled = true;
        var myInputSimulator = new InputSimulator();
        myInputSimulator.Keyboard.KeyDown(VirtualKeyCode.CONTROL);
        myInputSimulator.Keyboard.KeyPress(VirtualKeyCode.RIGHT);
     }
}

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

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