BIG阳
问题是标记为WPF,但到目前为止的答案是特定的WinForms和Win32。要在WPF中执行此操作,只需构造一个KeyEventArgs并在目标上调用RaiseEvent。例如,要将Insert键KeyDown事件发送到当前关注的元素: 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 }
);此解决方案不依赖于本机调用或Windows内部,并且应该比其他解决方案更可靠。它还允许您模拟特定元素上的按键。请注意,此代码仅适用于PreviewKeyDown,KeyDown,PreviewKeyUp和KeyUp事件。如果你想发送TextInput事件,你会这样做: 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 }
);另请注意:控件期望接收预览事件,例如,PreviewKeyDown应该在KeyDown之前使用target.RaiseEvent(...)将事件直接发送到目标,而不进行加速器,文本组合和IME等元处理。这通常是你想要的。另一方面,如果由于某种原因你真的要模拟实际的键盘键,你可以使用InputManager.ProcessInput()代替。