Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The question is tagged WPF but the answers so far are specific WinForms and Win32.</p> <p>To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:</p> <pre><code> 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), 0, key) { RoutedEvent=routedEvent } ); </code></pre> <p>This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.</p> <p>Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:</p> <pre><code> var text = "Hello"; var target = Keyboard.FocusedElement; var routedEvent = TextCompositionManager.TextInputEvent; target.RaiseEvent( new TextCompositionEventArgs( InputManager.Current.PrimaryKeyboardDevice, new TextComposition(InputManager.Current, target, text)) { RoutedEvent = routedEvent } ); </code></pre> <p>Also note that:</p> <ul> <li><p>Controls expect to receive Preview events, for example PreviewKeyDown should precede KeyDown</p></li> <li><p>Using target.RaiseEvent(...) sends the event directly to the target without meta-processing such as accelerators, text composition and IME. This is normally what you want. On the other hand, if you really do what to simulate actual keyboard keys for some reason, you would use InputManager.ProcessInput() instead.</p></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload