23

I'm trying to send a keystroke (Ctrl + t) for a browser control. But, SendKeys.Send() showed an error in a WPF application?

My questions are:

  1. Can I use the SendKeys.Send() method in a WPF application?
  2. Is there any alternative method for sending an automatic keystroke?
Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Adnan
  • 8,468
  • 9
  • 29
  • 45

2 Answers2

26

SendKeys is part of the System.Windows.Forms Namespace there is not an equivalent method in Wpf. You can not use the SendKeys.Send with WPF but you can use the SendKeys.SendWait method, if you add System.Windows.Forms to your project references. Your only other option would be to to PInvoke SendInput.

Be aware that both of these methods send data to the currently active window.

Mark Hall
  • 53,938
  • 9
  • 94
  • 111
25

I found a blog post describing use of InputManager. It allows you to simulate keyboard events in WPF.

/// <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 e = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key) 
      {
          RoutedEvent = Keyboard.KeyDownEvent
      };
      InputManager.Current.ProcessInput(e);

      // Note: Based on your requirements you may also need to fire events for:
      // RoutedEvent = Keyboard.PreviewKeyDownEvent
      // RoutedEvent = Keyboard.KeyUpEvent
      // RoutedEvent = Keyboard.PreviewKeyUpEvent
    }
  }
}
Katulus
  • 691
  • 1
  • 7
  • 12
  • 3
    This works great, but is there a way to send some modifiers with the key? (**Ctrl+V** for example?) Maybe you can make the KeyboardDevice think the modifier key is pressed somehow? Thanks! – P.W. Jan 21 '15 at 17:00
  • 3
    FYI this only enqueues the key event in the wpf application itself and can not be used to send keystrokes to other applications. – wischi Jan 15 '16 at 10:04
  • FYI- you need to add: PresentationCore and WindowsBase via Assembly ref – Netzmensch Sep 15 '21 at 11:00
  • I think this example is basically flawed because if it is used while processing a control- or alt-key combination the parameter 'Keyboard.PrimaryDevice' will hand over the currently pressed modifier keys together with the sent key. Say for example you are processing Ctrl-I and want to send a 'Key.Tab' you will end up sending Ctrl-Tab instead. The problem is that .NET doesn't give you access to the modifiers of a KeyboardDevice. There should added a method to access them. – AndresRohrAtlasInformatik Feb 27 '22 at 09:51