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
    • Onkel Olec
    • November 25th, 2013

    nice approach but it doesn’t work

  1. That is great of you! Thank you very much!

  2. Nice one. It worked for me after passing the key value instead of “Key.Down”

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: