Question

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. 
}
Was it helpful?

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.

OTHER TIPS

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 ;)

You're right, Jose, it's with MouseClick event. But you must add a little delegate:

this.button1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyMouseDouwn);

And use this method in your form:

    private void MyMouseDouwn(object sender, MouseEventArgs e) 
    {
        if (e.Button == MouseButtons.Right)
           this.Text = "Right";

        if (e.Button == MouseButtons.Left)
            this.Text = "Left";
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top