Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SendKeys.Send Method in WPF application

Tags:

c#

.net

wpf

I'm trying to send Keystroke(Ctrl+T) for browser control. But, SendKeys.Send() showed error in WPF application?? My question is

1) Can I use this method in WPF application?

2) Is there any alternative method fro sending automatic keystroke.

Thanks.

like image 335
Adnan Avatar asked Jul 20 '12 03:07

Adnan


2 Answers

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.

like image 62
Mark Hall Avatar answered Sep 30 '22 10:09

Mark Hall


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
    }
  }
}
like image 25
Katulus Avatar answered Sep 30 '22 11:09

Katulus