How to capture the spacebar press event using KeyeventHandler?

Shahid Sultan Minhas picture Shahid Sultan Minhas · Sep 18, 2013 · Viewed 29.3k times · Source

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.

Answer

Nick Andriopoulos picture Nick Andriopoulos · Sep 18, 2013
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == ' ')
            MessageBox.Show("space pressed");
    }