0

My problem I have few buttons in a form. I need to trigger those button on mouse click or the alt + the alphabet used as the hot key in it. I added & in front of the alphabet in the name property of the button. But my problem is that even if the alphabet is pressed without the use of alt key the below action is triggered. The below is the method which triggers the button named FirstMatch.

    public void firstMatch_Button_Click(object sender, EventArgs e)
    {

        Action_Raised(sender, "First Match");
    }
Vitor M. Barbosa
  • 3,286
  • 1
  • 24
  • 36
VVN
  • 501
  • 1
  • 9
  • 21

2 Answers2

3

First you need added & in front of the alphabet in the Text property not Name property of the button.

What you want to do is achieve by following code.

private void button1_Click(object sender, EventArgs e)
{
   if (ModifierKeys.HasFlag(Keys.Alt) || e.GetType() == typeof(MouseEventArgs))
   {
       MessageBox.Show("button is clicked.");
   }
}    
Dhaval kansagara
  • 551
  • 4
  • 17
0

You could change the property of your form KeyPreview to True

Now the form receives every key event first.

Then you can add an key up/down event to your form like this:

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    // Replace "Keys.A" with the key you want
    if (e.KeyCode == Keys.A && e.Alt)
    {
        this.firstMatch_Button.PerformClick();
    }
}

And please remove the & otherwise the button gets further triggered.

Nik Bo
  • 1,410
  • 2
  • 17
  • 29
  • sorry dint get you about removing the &. – VVN Aug 01 '17 at 13:20
  • You said, that you added a `&` in the text property of your button. You must remove it, otherwise it would be still triggered if you press the hot key without alt. – Nik Bo Aug 01 '17 at 13:22
  • i need it so that the hotkey is shown with an underline – VVN Aug 01 '17 at 13:25
  • That means Alias A will be underlined when alt is pressed. – VVN Aug 01 '17 at 13:25
  • Hmmm, I don't know if this is possible. With WPF that would work, but I don't know with WinForms. This question don't gont an answer for this problem. https://stackoverflow.com/questions/16868774 – Nik Bo Aug 01 '17 at 13:35