简体   繁体   中英

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;
    }
}

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);
    }

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); 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM