Search code examples
c#wpfmouseevent

How can I determine which mouse button raised the click event in WPF?


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 or Mouse.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 to MouseEventArgs, I receive errors.

XAML: <Button Name="myButton" Click="OnClick">

private void OnClick(object sender, EventArgs e)
{
//do certain thing. 
}

Solution

  • 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.