Objective:
To handle both mouse Left-Click and mouse Right-Click.
Problem:
The Click event is not raised when the Mouse Right-Button is clicked. It is only raised when the Mouse Left-Button is depressed then released.
Solution:
- Subscribe to both the Click, and the MouseRightButtonUp events.
Note A. The MouseRightButtonUp event is raised when the Mouse Right-Button is released over the button, irrespective of whether it was over the button when it was initially pressed.
Note B. It is not relevant to this situation, but you should note that the Click event of a Button object (pressing and releasing the Mouse Left-button) handles both the MouseLeftButtonDown and the MouseLeftButtonUp events, and therefore neither of those events can be handled when you use the mouse Left-button to click a Button object. If you do have a need to handle those actions separately you should subscribe to PreviewMouseLeftButtonDown, and/or PreviewMouseLeftButtonUp.
You can then either:
a. have 2 separate event handlers, one for each of these events, or
b. write an event handler that can handle both the Click and the MouseRightButtonUp events.
Note: A Click event needs a handler which accepts an argument of type RoutedEventArgs, whereas the MouseRightButtonUp event requires one of type MouseButtonEventArgs. Both RoutedEventArgs and MouseButtonEventArgs inherit from EventArgs. Therefore, make the handler accept EventArgs. The handler should then determine whether it has been passed a RoutedEventArgs (in which case it performs the actions required for a Left-click), or a MouseButtonEventArgs (in which case it performs the actions required for a Right-click).
Code example:
myButton.MouseRightButtonUp += MenuItemButton_Click;
myButton.Click += MenuItemButton_Click;
internal void MenuItemButton_Click(object sender, EventArgs e)
{
var clickedButton = sender as Button;
string EventArgsType = e.GetType().ToString();
//Remove leading qualification from Type ("System.Windows." or "System.Windows.Input.")
EventArgsType = type.Substring(EventArgsType.LastIndexOf('.') + 1);
switch (EventArgsType)
{
//Handle R-Click (RightMouseButtonUp)
case "MouseButtonEventArgs":
var MbeArgs = e as MouseButtonEventArgs;
//Do stuff
break;
//Handle L-Click (Click)
case "RoutedEventArgs":
var ReArgs = e as RoutedEventArgs;
//Do stuff
break;
default:
break;
}
}