I have a TextBox that only allows certain characters to be typed into it; I’m handling this logic in the PreviewTextInput event. If it’s a character that’s allowed, then the TextChanged event is fired, otherwise it cancels the TextChanged event.
I have another application that is opened on a second screen while this is running, however even if there is keyboard input while the other application is active, it should still update the currently focused TextBox on the main application. To do this, I added a listener to the OnKeyPress() event on the second application, which calls the PreviewTextInput event on the focused TextBox in the main application.
Here is the code:
private void ImageEventController_OnKeyPress(char c)
{
object focusedElement = this.CurrentKeyboardFocus;
if (focusedElement != null)
{
if (focusedElement is TextBox)
{
TextBox target = (TextBox)focusedElement;
if (target.IsEnabled)
{
string text = c.ToString();
var routedEvent = TextCompositionManager.PreviewTextInputEvent;
target.RaiseEvent(new TextCompositionEventArgs(
InputManager.Current.PrimaryKeyboardDevice,
new TextComposition(InputManager.Current, target, text)) { RoutedEvent = routedEvent });
}
}
}
}
When this is called, it goes through the PreviewTextInput event, however the TextChanged event never gets fired even if it’s a valid character. Is there any reason why TextChanged is not getting fired when PreviewTextInput is invoked programmatically?
UPDATE:
I added in this code to the bottom of my PreviewTextInput event listener:
if (!e.Handled)
{
textbox.Text = e.Text;
}
This forces the TextChanged event to fire and fixes the functionality when the second application has focus, however if the main application has focus it causes two TextBoxes to get updated when only pressing one button.
I was unable to figure out how to invoke the
TextChangedevent fromPreviewTextInput, but I did manage to accomplish what I needed to do:Instead of performing the logic to validate the key pressed is valid inside of the
PreviewTextInputevent, I pulled all of the logic out and put it into a public function. Then in myImageEventController_OnKeyPressevent I am using theLogicalTreeHelper.GetParent()method to find the necessary control. From there I call the public function to validate a valid key is pressed and if it is, I call theTextInputdirectly.