0
votes

Is there anyway to check if a menu item event is coming from a click in the menu or from a short cut key being pressed?

I've tried adding event handlers to the key press and key down events, however these events aren't being "fired" when it's a shortcut key that's pressed (They do work as expected when it's not a shortcut key). I couldn't find anything in the sender object that was different between the menu click or shortcut click.

4
Just out of curiosity, what's the point of differentiating click from key shortcut?ken2k
May I ask why you need such functionality? Normally I'd say that there should not be any difference between mouse click or key press, it is one task of the Menu Item to abstract from that.Desty
One computer is having a problem where it's seemingly randomly opening a form in the application that's tied to a F3 key. My suspicion is that the computer's keyboard is sending the key. However, since there are a handful of ways to open the form (Menu click, short cut, a drop down of "recently opened" forms, or just closing the form on top and going back to it) and the problem has never happened when I'm around I can't verify the problem. So I wanted to log when the F3 key was being pressed and see if it matched when the problem is coming up.GraeningM

4 Answers

1
votes

You can catch all key combinations by overriding ProcessCmdKey:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{
    if (keyData == (Keys.Control | Keys.F)) 
    {
        Console.WriteLine("My code ran from shortcut");
        myFunction();
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

private void ToolStripMenuItem_click(object sender ...)
{
  Console.WriteLine("My code ran from menu item");
  myFunction();
}

void myFunction()
{
  //your functionality here
}
1
votes

Well to get help, you should post what you have tried. (Your source)

You can use a enum for this:

enum Sender
{
    Shortcut,
    Menu
}

void MenuEvent(Sender sender)
{
    if (sender == Sender.Shortcut)
    {

    }
    else
    {

    }
}

//if you click from the menu
void btnMenuClick()
{
    MenuEvent(Sender.Menu);
}

//if you use shortcut
void OnShortcutEvent()
{
    MenuEvent(Sender.Shortcut);
}

Edit: I guess my answer was to vague so I edited the code. I hope its more clear now, but I must say the OP should give more details as well, such as posting some code.

0
votes

I see a single solution to this problem - override the ToolStripMenuItem's ProcessCmdKey method which is raised when a shortcut is processed. In this case, you can determine when a click was caused by a shortcut. Obviously, you need to use your own class of the ToolstripMenuItem instead of the standard one.

0
votes

Handle the MouseDown event to process your mouse-click.

menuItem.MouseDown += new MouseEventHandler(Process_Mouse_Click_Handler);

Handle the Click event to process your shortcut.

menuItem.Click+= new EventHandler(Process_Shortcut_Handler);