EditCategory
Input
EditQuestion
How can I simulate basic keyboard events?
EditAnswer
In order to simulate basic keyboard events, you simply need to build a KeyEventArgs object with the appropriate parameters and send it either directly to the element on which you wish to simulate the input or access the InputManager if the input needs to be simulated on the normal input recipient.
To build the KeyEventArgs, you need to specify the following at construction:
1. The KeyboardDevice that should be "simulated": If there is no specific device you wish to simulate, simply pass Keyboard.PrimaryDevice.
2. A PresentationSource object: You can obtain a valid PresentationSource by getting the KeyboardDevice.ActiveSource property.
3. A timestamp (can be 0).
4. The Key for which the input is simulated.
Once the KeyEventArgs object is constructed, you need to set the RoutedEvent member of the object to the input you wish to simulate. For example:
KeyEventArgs e = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource,
0, Key.Enter);
e.RoutedEvent = Keyboard.KeyDownEvent;
You can then sent the input simulation either by:
targetElement.RaiseEvent(e);
or
InputManager.Current.ProcessInput(e);
This will simulate the Enter key "Down" input for the "targetElement" object or for the currently focused element.
The types of input that can be simulated are as follows:
PreviewKeyDownEvent, KeyDownEvent, PreviewKeyUpEvent, KeyUpEvent.Note that this method will not simulate text input but only keystrokes.
For the simulation of text input, refer to related links.
EditRelated Links
Input: Simulating text input
C++ Help