OMGKurtNilsen
OMGKurtNilsen

Reputation: 5098

Form won't fire KeyDown

I have a form with a datagridview and a button. There will be more controls later.

Edit: I do have a contextmenustrip and a menustrip also.

The KeyDown event of the form won't fire unless the datagridview has focus. If the button has focus it doesn't fire. Even after loading the form and while it has focus, it will still not fire the KeyDown event.

How do I make sure the KeyDown event of the form will fire no matter where the focus is on the form?

I've googled and looked at other questions such as Windows.Form not fire keyDown event but can't figure this out.

Form load event:

    private void Kasse_Load(object sender, EventArgs e)
    {
        this.BringToFront();
        this.Focus();
        this.KeyPreview = true;
    }

Form KeyDown event:

private void Kasse_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Up:
            try
            {
                e.Handled = true;
                dataGridView1.Rows[dataGridView1.SelectedRows[0].Index - 1].Selected = true;
            }
            catch (Exception)
            {
            }
            break;
        case Keys.Down:
            try
            {
                e.Handled = true;
                dataGridView1.Rows[dataGridView1.SelectedRows[0].Index + 1].Selected = true;
            }
            catch (Exception)
            {
            }
            break;
    }
}

Upvotes: 0

Views: 1630

Answers (2)

drharris
drharris

Reputation: 11214

If you're trying to capture arrow keys, those are special control keys. You'll have to also override ProcessCmdKey

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{     
    if (keyData == Keys.Left) DoSomething();
    else if (keyData == Keys.Right) DoSomethingElse();
    else return base.ProcessCmdKey(ref msg, keyData); 
} 

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 942368

The cursor keys are used before the form's KeyDown event can fire. You need to detect them earlier. Override the ProcessCmdKey:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (keyData == Keys.Up) {
            // etc...
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

Upvotes: 3

Related Questions