Posts Tagged ‘ Keyboard ’

WPF – Send keys

Hi guys,

if you come from the WinForms age you might know the SendKeys class and the SendKeys.Send method, which allows you to send keys to the keyboard.
Meaning that you can simulate the pressing of a key.

But in WPF this class is no longer present. Instead of this class you can use the InputManager and feed it with the KeyEventArgs which will then be processed.
I created a small class which simplyfies this process.

public static class SendKeys
  {
    /// <summary>
    ///   Sends the specified key.
    /// </summary>
    /// <param name="key">The key.</param>
    public static void Send(Key key)
    {
      if (Keyboard.PrimaryDevice != null)
      {
        if (Keyboard.PrimaryDevice.ActiveSource != null)
        {
          var e1 = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Down) {RoutedEvent = Keyboard.KeyDownEvent};
          InputManager.Current.ProcessInput(e1);
        }
      }
    }
  }

You can simply call the SendKeys.Send method like you did it in WinForms.

Have fun!

Advertisements