How to catch a key press on a C# .NET form

前端 未结 2 842
太阳男子
太阳男子 2020-12-03 17:15

I have a parent form that contains a lot of controls. What I am trying to do is filter all of the key presses for that form. The trouble is that if the focus is on one of

相关标签:
2条回答
  • 2020-12-03 18:07

    This will only work on form, but not if any other component is in focus

    public partial class ChildForm : Form
    {
    
        public ChildForm()
        {       
           KeyPress += KeyPressHandler;
        }
    
        public KeyPressHandler(object sender, KeyPressEventArgs e)
        {
           if (_parent != null)
           {
               _parent.NotifyKeyPress(e);
           } 
        }
    }
    

    This will work even when other components are in focus

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.F1)
        {
            MessageBox.Show("You pressed the F1 key");
            return true;    // indicate that you handled this keystroke
        }
    
        // Call the base class
        return base.ProcessCmdKey(ref msg, keyData);
    }
    
    0 讨论(0)
  • 2020-12-03 18:09

    Set KeyPreview to true on your form and you will catch them: MSDN

    0 讨论(0)
提交回复
热议问题