How could I register a function to receive an event when the user presses the space bar in a text field?

Better yet, where in the fine manual should I be reading about how to do this? I'm not finding much by googling, and I think that I should be more familiar with the docs. Thanks.

Recommended Answers

All 7 Replies

My guess is that there is an event that is raised every time the text changes, find that event and add the proper handler. In your handler I'm guessing you'll need to use the EventArgs (or similar) information to determine if the space was entered.

Really, my guess is that you can google this pretty easily when you're looking through the events to find the one you want.

After a google search I hath found keydown, keypress, and keyup events for that control.

Those will definitely work just fine.

Also, I just tested this and it works.

commented: Thank you very much! +2

One of the possibilities is to use TextChanged event handler:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string lastChar = textBox1.Text.Substring(textBox1.Lenght -1, 1);
            if(lastChar == " ")
            {
                 MessageBox.Show("User has just pressed spaceBar.");
            }            
        }

Or use can use KeyPress event, where you will get the last character of whitespace:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
   if (!char.IsWhiteSpace(e.KeyChar))
   {
       MessageBox.Show("User has just pressed spaceBar.");
       //e.Handled = true;
   }
}
commented: Thank you. +2

My guess is that there is an event that is raised every time the text changes, find that event and add the proper handler. In your handler I'm guessing you'll need to use the EventArgs (or similar) information to determine if the space was entered.

Really, my guess is that you can google this pretty easily when you're looking through the events to find the one you want.

Please excuse me, but how does one "look through the events"? That seems to be the key step that I should have known how to take.

After a google search I hath found keydown, keypress, and keyup events for that control.

Those will definitely work just fine.

Also, I just tested this and it works.

Thank you very much!

One of the possibilities is to use TextChanged event handler:

Or use can use KeyPress event, where you will get the last character of whitespace:

Thank you Mitja. This does help!

You are welcome.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.