WPF应用程序中的SendKeys.Send方法

我正在尝试发送按键(Ctrl + T)进行浏览器控制。 但是, SendKeys.Send()在WPF应用程序中显示错误? 我的问题是

1)我可以在WPF应用程序中使用此方法吗?

2)是否有任何替代方法来发送自动击键。

谢谢。

SendKeys是System.Windows.Forms命名空间的一部分,在Wpf中没有等效的方法。 如果将System.Windows.Forms添加到项目引用中,则不能将SendKeys.Send与WPF一起使用,但可以使用SendKeys.SendWait方法。 您唯一的另一个选择是PInvoke SendInput 。

请注意,这两种方法都会将数据发送到当前活动的窗口。

我发现了一篇描述InputManager使用的博客文章 。 它允许您在WPF中模拟键盘事件。

 ///  /// Sends the specified key. ///  /// The key. 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 } } }