Search code examples
c#winformseventskeypress

c# specific sequence keypress event any where in form


I am a beginner at C# and would like some advice on how to solve the following problem:

I want to make an event to enable some text boxes when random press the following key "ctrl + v + a" anywhere in form.

  private void test_KeyDown(object sender, KeyEventArgs e)
    {
        if ((int)e.KeyData == (int)Keys.Control + (int)Keys.V + (int)Keys.A)
        {
            textbox1.Enabled = true;
            textbox2.Enabled = true;

        }
    }

The following code is not working.


Solution

  • So you want to do this Any Where In Form.
    The best way for doing this is override the ProcessCmdKey method of the Form.
    But it has some Limitations. You can use Control | Alt | Shift keys only with one more key.

    like:
    ctrl + V works
    ctrl + A works
    ctrl + alt + V works
    ctrl + alt + shift + V works

    ctrl + V + A does not work
    ctrl + alt + V + A does not work

    so you have to use another keys for example use ctrl + shift + V

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case (Keys.Control | Keys.Shift | Keys.V):
                    textbox1.Enabled = true;
                    textbox2.Enabled = true;
                    return true;
    
          // more keys if you want
    
                case (Keys.Control | Keys.H):
                    MessageBox.Show("Hello World!");
                    return true;
            }
    
            return base.ProcessCmdKey(ref msg, keyData);
        }