C# KeyDown problem

Started by
14 comments, last by Nypyren 17 years, 1 month ago
I can't get KeyDown method to work. I need my application to check answer when user clicks 'enter' on his keyboard, but unfortunately nothing happens. Here's the code:
 private void Answer_KeyDown(object sender, KeyEventArgs e)
        
        {
            if (e.KeyCode == Keys.Enter)
            {
                int result = 0;
                if (problemType == "+")
                {
                    result = no1 + no2;
                }
                else if (problemType == "-")
                {
                    result = no1 - no2;
                }
                else if (problemType == "*")
                {
                    result = no1 * no2;
                }

                if (Answer.Text == result.ToString())
                {
                    Feedback.Text = "Correct";
                }
                else
                {
                    Feedback.Text = "Incorrect";
                }
Advertisement
1. Make sure the control actually gets focus
2. If it's a TextBox or derived, there are "AcceptsReturn" and "AcceptsTab" properties that you need to set to 'true' if you want KeyDown events for those two keys.
3. In rare cases, override the "IsInputKey" method and return true for enter, otherwise return base.IsInputKey.
Quote:Original post by Nypyren
1. Make sure the control actually gets focus
2. If it's a TextBox or derived, there are "AcceptsReturn" and "AcceptsTab" properties that you need to set to 'true' if you want KeyDown events for those two keys.
3. In rare cases, override the "IsInputKey" method and return true for enter, otherwise return base.IsInputKey.


I didn't understood the get focus part. Can you tell a bit more about it?
Well, if it's a TextBox and you're successfully typing text into it, it has focus. If you can't tell if any input is getting to it at all then it might not.

Focus means that the control is the one selected to receive keyboard events.

Typically Focus is set when you click on a control or press the TAB key to move between controls.

Various controls have their "Selectable" style (see "Control.Setstyle") true or false, which can affect this.
Thanks and yes, it has focus and "AcceptsReturn" and "AcceptsTab" properties are set to 'true'. It's still doesn't work.
Did you put a breakpoint on your event handler to make sure that any other keys work?
..not really, i'm a beginner. :D
If AcceptsReturn is true and you're not getting the keydown it's possible that the event hasn't been hooked. Your function by itself won't be called unless you added it to the event, which requires something that looks like the following line:

Answer.KeyDown += new KeyEventHandler(Answer_Keydown);

(edit) oops
Well, there's no changes to my application again.

[Edited by - NotSlyPee on March 17, 2007 3:57:11 PM]
Might be time to post all of your code...

This topic is closed to new replies.

Advertisement