Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

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 instance of KeyEventArgs ( I don't know how )

The code in question is:

 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 compiler says:

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

The ide says:

Argument type IInputElement is not assignable to parameter type DependencyObject

And across StackOverflow I've found several answers directing to that answer but none of them address how to create the instance in first place.

How can I do that?

like image 329
OscarRyz Avatar asked May 30 '12 17:05

OscarRyz


1 Answers

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     } ); 
like image 143
OscarRyz Avatar answered Oct 03 '22 16:10

OscarRyz