1

Basically in a C# Windows Form Application I am working on I have 2 buttons I press button1 and button2.

How do I make it when I press 2 custom keys simultaneously(eg. CTRL+L) the program does the steps coded for button1? Keeping in mind that the window might not be active.

I have looked at this: Keypress To Simulate A Button Click in C# but I don't think this would work if the window isn't active, and its also only one button pressed not two.

Community
  • 1
  • 1

2 Answers2

1

In Form KeyUp Event and the Properties is KeyPressPreview = true you can achieve this task.

   private void Form_KeyUp(object sender, KeyEventArgs e)
   {
       if (e.KeyCode == Keys.L && e.Control)
       {
                yourButton.PerformClick();
                e.Handled = true;
        }
    }

or

if you want in Keypress Event

private void Form_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.L)
    {
            yourButton.PerformClick();
            e.Handled = true;
    }
}

EDIT:

I realized that the OP want to the keypress Event from his statement "but I don't think this would work if the window isn't active"

You probably must check this

How to set a Windows hook in Visual C# .NET

spajce
  • 7,044
  • 5
  • 29
  • 44
0

If you precede any character in the button text with &, and keep UseMnemonic to true,. the alt+character will serve as shortcut key.

For example, in your case change the text of the buttons to button&1 and button&2 respectively. Keep UserMnemonic = true. Now if you press alt+1 then button1 will be pressed and if you press alt+2, button2 will be pressed.

Also 1 and 2 respectively will be underlined.

Hope that helps.

Milind Thakkar
  • 980
  • 2
  • 13
  • 20