How can I determine which mouse button raised the click event in WPF?
Solution 1
If you're just using the Button's Click event, then the only mouse button that will fire it is the primary mouse button.
If you still need to know specifically whether it was the left or right button, then you can use the SystemInformation to obtain it.
void OnClick(object sender, RoutedEventArgs e)
{
if (SystemParameters.SwapButtons) // Or use SystemInformation.MouseButtonsSwapped
{
// It's the right button.
}
else
{
// It's the standard left button.
}
}
Edit: The WPF equivalent to SystemInformation is SystemParameters, which can be used instead. Though you can include System.Windows.Forms as a reference to obtain the SystemInformation without adversely effecting the application in any way.
Solution 2
You can cast like below:
MouseEventArgs myArgs = (MouseEventArgs) e;
And then get the information with:
if (myArgs.Button == System.Windows.Forms.MouseButtons.Left)
{
// do sth
}
The solution works in VS2013 and you do not have to use MouseClick event anymore ;)
paradisonoir
Updated on June 05, 2022Comments
-
paradisonoir almost 2 years
I have a button that I trigger
OnClick
whenever there is a click on that button. I would like to know which Mouse button clicked on that button?When I use the
Mouse.LeftButton
orMouse.RightButton
, both tell me "realsed" which is their states after the click.I just want to know which one clicked on my button. If I change
EventArgs
toMouseEventArgs
, I receive errors.XAML:
<Button Name="myButton" Click="OnClick">
private void OnClick(object sender, EventArgs e) { //do certain thing. }
-
rmoore almost 15 yearsThis is not correct for WPF, you'd need to use a MouseButtonEventArgs, and it doesn't have a button property, but instead every button's state.
-
paradisonoir almost 15 yearsbut even with private void OnClick(object sender, MouseButtonEventArgs e), it gives me the same error of error of "No overload for 'OnClick' matches delegate 'System.Windows.RoutedEventHandler'
-
paradisonoir almost 15 yearsthanks for the hint.Though mine is not a System.Windows.Form.It's an XAML window (WPF).
-
rmoore almost 15 years... yes, all my development is in XAML or Silverlight. This is for WPF, as you can clearly see by the RoutedEventArgs, System.Windows.Forms.Systeminformation is just the best and quickest way to get the Computer's system information in WPF.
-
Broken_Window almost 15 yearsI deleted the OnClick delegate.