How to get a combination of keys in c#

后端 未结 5 1361
旧巷少年郎
旧巷少年郎 2020-11-29 10:12

How can I capture Ctrl + Alt + K + P keys on a C# form? thanks

5条回答
  •  不知归路
    2020-11-29 10:49

    MessageFilters can help you in this case.

        public class KeystrokMessageFilter : System.Windows.Forms.IMessageFilter
        {
            public KeystrokMessageFilter() { }
    
            #region Implementation of IMessageFilter
    
            public bool PreFilterMessage(ref Message m)
            {
                if ((m.Msg == 256 /*0x0100*/))
                {
                    switch (((int)m.WParam) | ((int)Control.ModifierKeys))
                    {
                        case (int)(Keys.Control | Keys.Alt | Keys.K):
                            MessageBox.Show("You pressed ctrl + alt + k");
                            break;
                        //This does not work. It seems you can only check single character along with CTRL and ALT.
                        //case (int)(Keys.Control | Keys.Alt | Keys.K | Keys.P):
                        //    MessageBox.Show("You pressed ctrl + alt + k + p");
                        //    break;
                        case (int)(Keys.Control | Keys.C): MessageBox.Show("You pressed ctrl+c");
                            break;
                        case (int)(Keys.Control | Keys.V): MessageBox.Show("You pressed ctrl+v");
                            break;
                        case (int)Keys.Up: MessageBox.Show("You pressed up");
                            break;
                    }
                }
                return false;
            }
    
            #endregion
    
    
        }
    

    Now in your C# WindowsForm, register the MessageFilter for capturing key-strokes and combinations.

    public partial class Form1 : Form
    {
        KeystrokMessageFilter keyStrokeMessageFilter = new KeystrokMessageFilter();
    
        public Form1()
        {
            InitializeComponent();
        }       
        private void Form1_Load(object sender, EventArgs e)
        {
            Application.AddMessageFilter(keyStrokeMessageFilter);
        }
    }
    

    Somehow it only detects Ctrl + Alt + K. Please Read the comment in MessageFilter code.

提交回复
热议问题