简体   繁体   English

WPF,如何检测RichTextBox中的空格键

[英]WPF, How to detect Spacebar press in RichTextBox

In WPF, I have a RichTextBox with a flow document inside. 在WPF中,我有一个RichTextBox,其中带有流文档。 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. 如果按F,例如会显示一个带有F的消息框,但是当按下空格键时,插入标记会移至下一个位置。

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: 您可以通过像这样处理PreviewKeyDownPreviewKeyUp事件来检测空格字符:

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? 至于为什么PreviewTextInput事件忽略空格字符,您可以在“ 为什么PreviewTextInput无法处理空格?”中找到一些有趣的信息 post and the links found there. 帖子和找到的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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