Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I press a button in GUI.Button displays a message after I press it. But the keydown event does not work properly. Instead, it takes both "spacebar" and "Enter" keys along with the set keys in WinForms

What I have tried:

//As mentioned
this.KeyPreview = true;

//
this.KeyDown += new KeyEventHandler(Form1_KeyDown);


//IN KEYDOWN
if (e.KeyCode == Keys.H)
         {
             button1.PerformClick();
         }
Posted
Updated 16-Mar-17 1:33am
v7
Comments
OriginalGriff 16-Mar-17 7:00am    
This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind. So try to explain exactly what you tried, which keypress and keydown events you mean, and what happens that you didn't expect.
The better info you give us, the better response we can give you.
Use the "Improve question" widget to edit your question and provide better information.
Graeme_Grant 16-Mar-17 7:02am    
Please update the question with clear and concise details by clicking on Improve question to add more info to the question.
[no name] 16-Mar-17 7:03am    
"why my keypress ", because you did something wrong. What that is we can't tell you as we cannot read your mind or magically view your computer monitor.
Graeme_Grant 16-Mar-17 7:22am    
Where is the keypress being fired from? too hard to tell. How is it not working properly??

1 solution

If I insert that code into a test app:
C#
public frmMain()
    {
    InitializeComponent();
    this.KeyPreview = true;
    this.KeyDown += new KeyEventHandler(frmMain_KeyDown);
    }

C#
private void frmMain_KeyDown(object sender, KeyEventArgs e)
    {
    if (e.KeyCode == Keys.H)
        {
        myButton.PerformClick();
        }
    }

C#
private void MyButton_Click(object sender, EventArgs e)
    {
    Console.WriteLine("Done");
    }
Then every time I press "H" on the keyboard while the form has the focus, it prints "Done" in the output pane - which is what I expect.
So what are you doing that is different to me, given that I copy'n'pasted your code...
 
Share this answer
 
Comments
Graeme_Grant 16-Mar-17 7:36am    
Just beat me to the punch!

I would also do the following:
private void frmMain_KeyDown(object sender, KeyEventArgs e)
    {
    if (e.KeyCode == Keys.H)
        {
        e.Handled = true; / **
        myButton.PerformClick();
        }
    }
OriginalGriff 16-Mar-17 7:55am    
So would I - but in this case I wanted exactly the code he was using.
Graeme_Grant 16-Mar-17 8:27am    
I just mentioned it as he may not be aware and other odd behavior may pop up.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900