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

时间:2012-05-30 17:10:07

标签: 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中,我找到了几个指向答案的答案,但没有一个解决如何在第一时间创建实例。

我该怎么做?

4 个答案:

答案 0 :(得分:51)

phewwww

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

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

答案 1 :(得分:10)

如果有人试图创建KeyEventArgs以用于单元测试,您会发现Keyboard.PrimaryDevice.ActiveSource为null ..并在您尝试使用它时抛出异常

模拟PresentationSource是一个可行的解决方案(需要sta):

[Test]
[RequiresSTA]
public void test_something()
{
  new KeyEventArgs(
    Keyboard.PrimaryDevice,
    new Mock<PresentationSource>().Object,
    0,
    Key.Back);
}

答案 2 :(得分:1)

单元测试一个viewmodel我必须使用OscarRyz和Elijah W. Gagne的组合来回答这个问题。

    [TestMethod]
    public void method_event_expected()
    {
        this.objectUnderTest.TestMethod(
            new KeyEventArgs(Keyboard.PrimaryDevice, new HwndSource(0, 0, 0, 0, 0, "", IntPtr.Zero), 0, Key.Oem3)
            {
                RoutedEvent = Keyboard.KeyDownEvent
            });

        Assert.IsTrue(...)
    }

Keyboard.PrimaryDevice.ActiveSource为null所以我不得不用虚拟窗口伪造它然后我还需要分配RoutedEvent。

答案 3 :(得分:-1)

var kea = new KeyEventArgs(
    Keyboard.PrimaryDevice,
    new HwndSource(0, 0, 0, 0, 0, "", IntPtr.Zero),
    0,
    Key.Enter)
    {
        RoutedEvent = UIElement.KeyUpEvent
    };