C# 如何使用 KeyeventHandler 捕获空格键按下事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18874380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:29:23  来源:igfitidea点击:

How to capture the spacebar press event using KeyeventHandler?

c#.netkeyeventkey-eventskeyeventargs

提问by Shahid Sultan Minhas

I have a Form with a rich text box in which i want to do the following:

我有一个带有富文本框的表单,我想在其中执行以下操作:

When user presses the spacebar button (Currently i am doing it with keydown event but want to use key press event but it doesn't provide e.keycode), a function should be called in which this logic is to be implemented:

当用户按下空格键时(目前我正在使用 keydown 事件但想使用按键事件但它不提供 e.keycode),应该调用一个函数来实现这个逻辑:

last written word is to be fetched and is to be looped through the text of rich text box in order to find its number of occurrences in a rich text box.

最后写入的单词将被提取并循环遍历富文本框的文本,以便找到它在富文本框中出现的次数。

What i have done so far is:

到目前为止我所做的是:

private void textContainer_rtb_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Space)
        {
            String abc = this.textContainer_rtb.Text.Split(' ').Last();
            chkWordRepeat(abc);
        }
    }
public void chkWordRepeat(String lastWordToFind)
    {
        int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;
        MessageBox.Show("Word: " + lastWordToFind + "has come: " + count + "times");
    }

Please let me know if the above mentioned logic is correct or not And how can i attach this logic with key press event for spacebar? If not then please help me implementing!

请让我知道上述逻辑是否正确以及如何将此逻辑与空格键的按键事件附加在一起?如果没有,请帮我实施!

Thanks in advance.

提前致谢。

回答by Nick Andriopoulos

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == ' ')
            MessageBox.Show("space pressed");
    }

回答by CheapD AKA Ju

My opinion is :

我的意见是:

public Dictionary<string, int> data;

private void textContainer_rtb_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Space)
    {
        String abc = this.textContainer_rtb.Text.Split(' ').Last();
        chkWordRepeat(abc);
    }
}

public void chkWordRepeat(string wrd)
{
    bool present = false;
    foreach (string key in data.Keys)
    if (wrd == key)
    {
        present = true;
        data[wrd]++;
    }

    if (!present)
            data.Add(wrd, 1);
}