Trouble creating KeyDown event in Panel

人盡茶涼 提交于 2019-12-10 23:24:27

问题


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


来源:https://stackoverflow.com/questions/20079373/trouble-creating-keydown-event-in-panel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!