Search code examples
c#winformskeycode

Is it possible to make a two letter keycode in windows form c#


I've tried this one but it's not working.

     if (e.Control && e.KeyCode == Keys.B &&e.KeyCode == Keys.R )
        {
            btn.PerformClick();
        }

Solution

  • One way to make sure that B is pressed and then followed by R would be to have a bool variable that indicates that B was pressed.

    Here's a full example:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            this.KeyPreview = true;
            this.KeyDown += new KeyEventHandler(Form1_KeyDown);
        }
    
        bool readyForRKey;
    
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (readyForRKey && e.KeyCode == Keys.R)
            {
                btn.PerformClick();
            }
    
            readyForRKey = (e.KeyData == (Keys.Control | Keys.B));
        }
    }
    

    This will work if the user presses (Ctrl+B, R) regardless of whether or they release the Ctrl key before pressing R.

    If, on the other hand, you want to make sure that both B and R are pressed at the same time, this answer might help you.