简体   繁体   中英

WPF, How to detect Spacebar press in RichTextBox

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM