Reputation: 2910
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.
}
Upvotes: 5
Views: 17375
Reputation: 1
OnClick is called after a mouse button is pressed and then released. At the time of the call, the key has already been released. It is necessary to remember the state when clicking and reset the state when processing OnClick, as well as after processing a double click.
Upvotes: 0
Reputation: 1843
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 ;)
Upvotes: 7
Reputation: 15403
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.
Upvotes: 2
Reputation: 2093
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";
}
Upvotes: 0