Reputation: 3795
In WPF, I have a RichTextBox with a flow document inside. I need to know when the user presses a spacebar. The code below works and shows a messagebox each time a key is pressed but not for spacebar. If you press F e.g. a messagebox with F is displayed but when space is pressed the caret just moves to the next position.
private void RichTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
MessageBox.Show(e.Text);
}
What am I missing here? Thanks for your time :)
Upvotes: 1
Views: 1646
Reputation: 69959
You can detect the space character by handling the PreviewKeyDown
or PreviewKeyUp
events like this:
private void PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
// The user pressed the space bar
}
}
As to why the PreviewTextInput
event ignores the space character, you can find some interesting information in the Why does PreviewTextInput not handle spaces? post and the links found there.
Upvotes: 2