-->

Trouble creating KeyDown event in Panel

2019-07-10 03:05发布

问题:

I am currently working on winform that has a panel on it. I need to be able to use the up, down, left and right arrows on the panel and get something to happen.

I tried adding the event with this line of code:

            (MainPanel as Control).KeyDown += 
                                 new KeyEventHandler(panelKeyPressEventHandler);

With this KeyDown code:

        public void panelKeyPressEventHandler(object sender, System.Windows.Forms.KeyEventArgs e)
    {

        MessageBox.Show("Here I am!");

        switch (e.KeyCode)
        {
            case Keys.L:
                {

                    break;
                }
            case Keys.R:
                {

                    break;
                }
            case Keys.Up:
                {
                    break;
                }
            case Keys.Down:
                {
                    break;
                }
            case Keys.Right:
                {
                    break;
                }
            case Keys.Left:
                {
                    break;
                }

        }
    }

Thus far, even when I guarantee focus is set on the panel, I am unable to get it to enter this KeyDown event function for anything. :( I can hit keys all day long and nothing happens.

Does anyone have any suggestion on the best way to handle up,down,left and right arrows being pressed when a panel has focus?

Thank you!

回答1:

Panel control cannot get focus and not selectable also. Focused controls can only get "key events". You likely need to override ProcessCmdKey in your form or UserControl.

You need to set KeyPreview = true

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch(keydata)
    {
        case Keys.Up:
             break;
        ...
    }
    return base.ProcessCmdKey(ref msg, keyData);
}