2
votes

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
What is it you want to have happen? It's likely that you would want to put some other control in there, Dock.Fill it, and then react on that instead. You can do stuff with a Panel, but it's more useful for just holding the stuff you do want to play with.DonBoitnott
possible duplicate of Panel not getting focusHans Passant

1 Answers

3
votes

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