I need to send keystrokes to a RichTextBox which at the and should execute some commands like ToggleBold or SelectAll etc.
I call the following code in a loop to iterate through SomeEvent and SomeKey pairs.
PresentationSource presentationSource = PresentationSource.FromVisual(RichTextBoxControl);
if (presentationSource == null)
{
return;
}
if(SomeEvent == KeyDownEvent)
{
//InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, presentationSource, 100, SomeKey) { RoutedEvent = PreviewKeyDownEvent });
InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, presentationSource, 100, SomeKey) { RoutedEvent = KeyDownEvent });
}
else if (SomeEvent == KeyUpEvent)
{
//InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, presentationSource, 100, SomeKey) { RoutedEvent = PreviewKeyUpEvent });
InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, presentationSource, 100, SomeKey) { RoutedEvent = KeyUpEvent });
}
For example to activate ToggleBold I call following pairs in a loop:
KeyDownEvent, Keys.Control
KeyDownEvent, Keys.B
KeyUpEvent, Keys.B
KeyUpEvent, Keys.Control
I have tried KeyDownEvent - KeyUpEvent, PreviewKeyDownEvent - PreviewKeyUpEvent, and PreviewKeyDownEvent - KeyDownEvent - PreviewKeyUpEvent - KeyUpEvent, but none of them worked.
The RichTextBox actually catches the events but it does not react to them. This is also the case if I send alphanumeric characters (They are not printed on RichTextBox). However if I send Keys.Back it actually recognizes and deletes a character from the text.
The solutions like SendKeys and keybd_event are not applicable since the program will be on the background while the keystrokes are sent.
Is there a way to send keystrokes to a control like they really are sent by the user?
Aucun commentaire:
Enregistrer un commentaire