Reading keyboard key presses on WinForm

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • JDeats

    Reading keyboard key presses on WinForm

    I have a WinForm with a single command button in the middle, I have
    added a KeyDown event handler to the form and the method for this is:

    private void Form2_KeyDown(o bject sender, KeyEventArgs e)
    {
    MessageBox.Show (e.KeyCode.ToSt ring());
    }

    When I run the program and tap on the keyboard nothing happens, I set
    a break-point and it is never reached. So I tried using the KeyPress
    event instead and the same thing happens.

    private void Form2_KeyPress( object sender, KeyPressEventAr gs
    e)
    {
    MessageBox.Show (e.KeyChar.ToSt ring());
    }

    If I remove the button, both methods are called.... So it appears any
    control placed on the page could have focus and prevent my general,
    form-level keypress event handler from working as I would like. The
    actual project I'm trying to incorporate this into could have many
    controls on it, is there a general way to trap a key press by the user
    regardless of which control on the form has focus, without adding a
    keydown or keypress event handler for every control?

  • Brian Schwartz

    #2
    Re: Reading keyboard key presses on WinForm

    Take a look at the form's KeyPreview property.

    --
    Brian Schwartz
    FishNet Components

    Fish Grid .NET Light: Powerful Layouts for Small Datasets


    "JDeats" <Jeremy.Deats@g mail.comwrote in message
    news:1178830440 .864910.73220@u 30g2000hsc.goog legroups.com...
    I have a WinForm with a single command button in the middle, I have
    added a KeyDown event handler to the form and the method for this is:
    >
    private void Form2_KeyDown(o bject sender, KeyEventArgs e)
    {
    MessageBox.Show (e.KeyCode.ToSt ring());
    }
    >
    When I run the program and tap on the keyboard nothing happens, I set
    a break-point and it is never reached. So I tried using the KeyPress
    event instead and the same thing happens.
    >
    private void Form2_KeyPress( object sender, KeyPressEventAr gs
    e)
    {
    MessageBox.Show (e.KeyChar.ToSt ring());
    }
    >
    If I remove the button, both methods are called.... So it appears any
    control placed on the page could have focus and prevent my general,
    form-level keypress event handler from working as I would like. The
    actual project I'm trying to incorporate this into could have many
    controls on it, is there a general way to trap a key press by the user
    regardless of which control on the form has focus, without adding a
    keydown or keypress event handler for every control?
    >

    Comment

    Working...