c# - 如何在 WPF 中创建 KeyEventArgs 对象(与 SO 答案相关)

标签 c# wpf

我找到了这个看起来像我需要的答案:

How can I programmatically generate keypress events in C#?

除了我无法创建 KeyEventArgs 的实例(我不知道如何创建)

有问题的代码是:

 var key = Key.Insert;                    // Key to send
  var target = Keyboard.FocusedElement;    // Target element
  var routedEvent = Keyboard.KeyDownEvent; // Event to send

  target.RaiseEvent(
    new KeyEventArgs(
      Keyboard.PrimaryDevice,
      PresentationSource.FromVisual(target), //<--- HERE, I can't
      0,
      key)
    { RoutedEvent=routedEvent }
  );

编译器说:

The best overloaded method match for
'System.Windows.PresentationSource.FromDependencyObject(System.Windows.DependencyObject)'
 has some invalid arguments

ide 说:

参数类型 IInputElement 不可分配给参数类型 DependencyObject

在 StackOverflow 中,我发现了几个针对该答案的答案,但没有一个首先解决如何创建实例的问题。

我该怎么做?

最佳答案

呜呜呜

我找到了:必须使用Keyboard.PrimaryDevice.ActiveSource

InputManager.Current.ProcessInput(
    new KeyEventArgs(Keyboard.PrimaryDevice,
        Keyboard.PrimaryDevice.ActiveSource,
        0, Key.Tab)
    {
       RoutedEvent = Keyboard.KeyDownEvent
    }
);

关于c# - 如何在 WPF 中创建 KeyEventArgs 对象(与 SO 答案相关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10820990/

相关文章:

c# - 在自己的/创建线程上通知事件订阅者

c# - `PrintQueue.AddJob` 没有完成

c# - 如何为绑定(bind)正确设置 WPF UserControl

c# - UserControl 绑定(bind)到 observablecollection 不起作用

c# - 具有自定义 MembershipProvider 且没有 X.509 证书的 WCF,可能吗?

c# - c#线程间数据传递

asp.net - 如何以WPF格式捕获网页(在WebBrowser控件内打开)的按钮单击事件?

wpf - 梯形上的 C#/WPF 图像转换

wpf - 绑定(bind)到 ObservableCollection 是一个非常顽皮的男孩

c# - 这些静态变量的可能替代方案是什么?