How to capture the spacebar press event using KeyeventHandler?

邮差的信 提交于 2021-02-08 10:55:34

问题


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:

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.


回答1:


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



回答2:


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);
}


来源:https://stackoverflow.com/questions/18874380/how-to-capture-the-spacebar-press-event-using-keyeventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!