Catching Function key at form level without menu item conflict

721 views Asked by At

I have developed a Windows Forms application (.NET 4.6, VS.2017) and I have two forms, the main form and a non-modal form. In both forms I need to catch the user pressing the F2 key. This is by the way the only function key in use by the application, no other shortcut defined for any other function key.

In both forms I enabled Form.KeyPreview which by default is false. Then I also implemented the KeyDown event and in it I check whether it is my function key:

private void myView_KeyDown(object sender, KeyEventArgs e)
{
   if (e.KeyCode == Keys.F2)  // breakpoint placed here!
   {
        // perform action
        e.Handled = true;
   }
}

Do notice that I have placed a breakpoint on the IF statement checking which key has been pressed and not inside the action block.

Now in my non-modal form that works absolutely fine no matter which function key I choose.

However, the main form exhibits a weird behavior with the same code. If in the main form I use 'e.KeyCode == Keys.F3' then the breakpoint triggers for all other function keys pressed EXCEPT F3.

So, I then changed the if statement to instead check for F2 rather than F3. But now with that change the breakpoint triggers for all function keys except F2, so F3 that was not working before (when checking for F3) now works but F2 doesn't.

It does not matter which Function Key I chose, the breakpoint will trigger for ALL function keys EXCEPT the one I chose.

Here is the catch though... In one of my ToolStripMenuItems I also placed that same Function Key as shortcut because they fulfill the same action (then the user does not have to press Alt G and then Alt something else but instead use F2 directly.

So, if I remove the shortcut from the ToolStripMenuItem then my form KeyDown works as expected BUT then there is no visual hint to the user that he can use F2 to accomplish that function. The strange thing here is also that neither the toolstripmenuitem nor the form react to the selected function key.

What can I do then to have the shortcut work for both the tool strip menu item and at form level?

1

There are 1 answers

0
Guillaume CR On

After testing setting a MenuStripITem's ShortcutKeys property to 'F2' I was able to get the behavior you mention. Clicking on the menu item or hitting F2 both executed the button's handler code. I did not change the KeyPreview property nor did I implement KeyDown. I think getting rid of this unnecessary code will help you.