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
var kea = new KeyEventArgs(
Keyboard.PrimaryDevice,
new HwndSource(0, 0, 0, 0, 0, "", IntPtr.Zero),
0,
Key.Enter)
{
RoutedEvent = UIElement.KeyUpEvent
};
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);
}
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
}
);
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.
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);