1

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 :)

SeyedPooya Soofbaf
  • 2,654
  • 2
  • 29
  • 31
iAteABug_And_iLiked_it
  • 3,725
  • 9
  • 36
  • 75

1 Answers1

2

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.

Community
  • 1
  • 1
Sheridan
  • 68,826
  • 24
  • 143
  • 183