如何以編程方式在C#中生成按鍵事件?如何以編程方式創建一個模擬鍵盤上按鍵的事件?
3 回答
BIG陽
TA貢獻1859條經驗 獲得超6個贊
問題是標記為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()代替。
- 3 回答
- 0 關注
- 647 瀏覽
添加回答
舉報
0/150
提交
取消
