Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have the following code in my Windows Form code and for whatever reason the key presses aren't being picked up because my code isn't being executed. For example, pressing Space will hide the window. It doesn't.

C#
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar.Equals(Keys.Space))
    {
        this.Hide();
        restoreToolStripMenuItem.Enabled = true;
    }
    else if (e.KeyChar.Equals(Keys.M))
    {
        //If the menu is hidden, show it. Otherwise, hide it.
        if (menuTrayPanel.Tag.Equals("hidden"))
        {
            animationTimer.Tick += new EventHandler(displayMenu);
            animationTimer.Tick -= new EventHandler(hideMenu); //Don't trigger the hideMenu void when displaying it
            displayMenu(sender, e);
        }
        else
        {
            animationTimer.Tick -= new EventHandler(displayMenu);
            animationTimer.Tick += new EventHandler(hideMenu); //Same as with displaying, but the other way
            hideMenu(sender, e);
        }
    }
}
Posted

Some control that has the focus may consume the event so it isn't invoked for the form. There is some property in a windows form that will allow the form to listen in on events that were not raised on the form itself. The property has preview in its name. Since I'm writing this from my mobile I can't give you more details. Please google for winform event(s) preview.

Hope that helps.

MRB
 
Share this answer
 
Did you attach your method to the event?
 
Share this answer
 
Comments
Manfred Rudolf Bihy 5-Dec-11 15:26pm    
Moved from non answer:
Yes, I did. I double-clicked the even in the Properties window
Tim Groven 6-Dec-11 8:10am    
What control has the focus when the space bar is pressed? If it's a child control, the child control is probably consuming the event.

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