How to capture the spacebar press event using KeyeventHandler?

29,951
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == ' ')
            MessageBox.Show("space pressed");
    }
Share:
29,951
Shahid Sultan Minhas
Author by

Shahid Sultan Minhas

Updated on November 25, 2022

Comments

  • Shahid Sultan Minhas
    Shahid Sultan Minhas over 1 year

    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.

  • Shahid Sultan Minhas
    Shahid Sultan Minhas almost 11 years
    Event has been handled successfully but what about second part that fetches the last written word and search its number of occurrences in a rich text box?