简体   繁体   English

表单不会触发KeyDown

[英]Form won't fire KeyDown

I have a form with a datagridview and a button. 我有一个带有datagridview和按钮的表单。 There will be more controls later. 以后会有更多控件。

Edit: I do have a contextmenustrip and a menustrip also. 编辑:我确实有一个contextmenustrip和menustrip。

The KeyDown event of the form won't fire unless the datagridview has focus. 除非datagridview具有焦点,否则窗体的KeyDown事件不会触发。 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. 即使在加载窗体并使其具有焦点后,它仍不会触发KeyDown事件。

How do I make sure the KeyDown event of the form will fire no matter where the focus is on the form? 如何确保无论焦点在窗体上的哪个位置,都会触发该窗体的KeyDown事件?

I've googled and looked at other questions such as Windows.Form not fire keyDown event but can't figure this out. 我已经用谷歌搜索并查看了其他问题,例如Windows.Form不会触发keyDown事件,但无法弄清楚。

Form load event: 表单加载事件:

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

Form KeyDown event: 表单KeyDown事件:

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. 在可以触发窗体的KeyDown事件之前使用光标键。 You need to detect them earlier. 您需要更早发现它们。 Override the ProcessCmdKey: 覆盖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 您还必须重写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); 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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