How to create a KeyEventArgs object in WPF ( related to a SO answer )

前端 未结 5 1761
野趣味
野趣味 2020-12-29 04:39

I\'ve found this answer which look like what I need:

How can I programmatically generate keypress events in C#?

Except for the fact I can\'t create an insta

相关标签:
5条回答
  • 2020-12-29 04:57
    var kea = new KeyEventArgs(
        Keyboard.PrimaryDevice,
        new HwndSource(0, 0, 0, 0, 0, "", IntPtr.Zero),
        0,
        Key.Enter)
        {
            RoutedEvent = UIElement.KeyUpEvent
        };
    
    0 讨论(0)
  • 2020-12-29 05:00

    If anyone is trying to create the KeyEventArgs for use in a unit test you'll find that Keyboard.PrimaryDevice.ActiveSource is null.. and throws an exception when you try to use it.

    Mocking a PresentationSource is a workable solution (requires sta):

    [Test]
    [RequiresSTA]
    public void test_something()
    {
      new KeyEventArgs(
        Keyboard.PrimaryDevice,
        new Mock<PresentationSource>().Object,
        0,
        Key.Back);
    }
    
    0 讨论(0)
  • 2020-12-29 05:05

    phewwww

    I've found it: Keyboard.PrimaryDevice.ActiveSource has to be used

    InputManager.Current.ProcessInput(
        new KeyEventArgs(Keyboard.PrimaryDevice,
            Keyboard.PrimaryDevice.ActiveSource,
            0, Key.Tab)
        {
           RoutedEvent = Keyboard.KeyDownEvent
        }
    );
    
    0 讨论(0)
  • 2020-12-29 05:08

    To unit test a viewmodel I had to use a combination of OscarRyz and Elijah W. Gagne answer to make this work.

        [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 was null so I had to fake it with a dummy window and then I also needed the RoutedEvent to be assigned.

    0 讨论(0)
  • 2020-12-29 05:11

    Similar to Bill Tarbell's answer, you can also create a dummy System.Windows.Interop.HwndSource, like so:

    var kea = new KeyEventArgs(
        Keyboard.PrimaryDevice, 
        new HwndSource(0, 0, 0, 0, 0, "", IntPtr.Zero), // dummy source
        0, 
        key);
    
    0 讨论(0)
提交回复
热议问题