Programmatically generate keydown presses for WPF unit tests Programmatically generate keydown presses for WPF unit tests wpf wpf

Programmatically generate keydown presses for WPF unit tests


You can extend the PresentationSource class like this:

public class FakePresentationSource : PresentationSource{    protected override CompositionTarget GetCompositionTargetCore()    {        return null;    }    public override Visual RootVisual { get; set; }    public override bool IsDisposed { get { return false; } }}

And use it like this:

var uiElement = new UIElement();uiElement.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, new FakePresentationSource(), 0, Key.Delete) {     RoutedEvent = UIElement.KeyDownEvent });


A quicker solution for unit tests is just to mock the PresentationSource object. Note that it requires an STA thread. Sample uses Moq and nunit.

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


Figured this out after reading this post.

Basically, you need to put your control inside a Window and call Window.Show() on it. The post mentioned an WPF bug, but I didn't encounter this in WPF 4.

After calling Window.Show(), the presentation source will no longer be null and you will be able to send keys to the control.