简体   繁体   中英

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?

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...).

Full source code in the public repo (commented the other alternative solution).

Or use ready github project for .Net, Windows Input Simulator

It also uses "user32.dll" functions by marshaling

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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