CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: KeyDown event

  1. #1
    Join Date
    Jan 2002
    Posts
    87

    KeyDown event

    Dear CodeGurus,

    I am trying to assign some actions to the KeyDown event on my form (to any key, say 'a'), so I try the following:

    HTML Code:
            private void Form1_KeyDown(object sender, KeyEventArgs e)
            {
                if(e.KeyCode != Keys.ShiftKey && e.KeyCode != Keys.ControlKey)
                    MessageBox.Show(String.Format("{0:D}", e.KeyCode), "Message");
            }
    My understanding that this should pop-up the Message Window any time when I press any character key on the keyboard. However, this works only if I have no controls on the form, if there is anything on it I get nothing. Can anybody explain why this is happening? How can I get it to work???

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: KeyDown event

    Because if you have a control on your form the KeyDown event is not passed through to your form by default. So, you can catch the KeyDown event in a specific control or, if you want this to be global, set the "KeyPreview" property of your form to true. This will cause the keyboard events to be passed to the parent form.
    If you liked my post go ahead and give me an upvote so that my epee.... ahem, reputation will grow.

    Yes; I have a blog too - http://the-angry-gorilla.com/

  3. #3
    Join Date
    Jan 2002
    Posts
    87

    Re: KeyDown event

    Thank you!!! It works!

  4. #4
    Join Date
    Jun 2008
    Posts
    2,477

    Re: KeyDown event

    No problem.

    BTW, KeyCode is an enum, so checking for something like e.KeyCode != Keys.Shift is insufficient because you can hold shift AND press a key. You need to use boolean operations to determine if Shift was ONE of the keys that was pressed. For example:

    Code:
    private void Form1_KeyDown(object sender, KeyEventArgs e
    {
        if( (e.KeyCode & Keys.Shift ) != Keys.Shift )
        {
            //...
        }
    }
    If you liked my post go ahead and give me an upvote so that my epee.... ahem, reputation will grow.

    Yes; I have a blog too - http://the-angry-gorilla.com/

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured