Search code examples
c#wpfwpf-controlsmouse

How can I check if mouse button is left or right in wpf C#?


I'm trying this code actually I have created only one Eventhandler that is on Click="button_Click".

XAML:

<Window x:Class="WPFAPP.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WPFAPP"
    mc:Ignorable="d"
    Title="Window1" Height="447.625" Width="562">

    <Grid>
        <Button x:Name="btn1" Content="Button1" Click="button_Click" HorizontalAlignment="Left" Margin="26,22,0,0" VerticalAlignment="Top" Width="75"/>
        <Button x:Name="btn2" Content="Button2" Click="button_Click" HorizontalAlignment="Left" Margin="26,61,0,0" VerticalAlignment="Top" Width="75"/>
        <Button x:Name="btn3" Content="Button3" Click="button_Click" HorizontalAlignment="Left" Margin="26,100,0,0" VerticalAlignment="Top" Width="75"/>
        <Button x:Name="btn4" Content="Button4" Click="button_Click" HorizontalAlignment="Left" Margin="26,137,0,0" VerticalAlignment="Top" Width="75"/>
        <Button x:Name="btn5" Content="Button5" Click="button_Click" HorizontalAlignment="Left" Margin="26,174,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window> 

Code Behind C#:

private void button_Click(object sender, RoutedEventArgs e)
{
    Button button = (Button)sender;
    if(e.Equals(Mouse.RightButton))
    {
        button.ClearValue(Button.BackgroundProperty);
        button.Background = Brushes.Green;
    } 
} 

Solution

  • Click is only designed for the most limited interaction, if you use the more advanced mouse events you then get a MouseButtonEventArgs which gives you all details about the event.

    the reason for this is that Click isn't a mouse event, you could also trigger it with a touch, stylus, you can even trigger it with the keyboard by pressing Return while highlighted

    so try MouseDown, MouseUp or DoubleClick instead

    eg

    <Button MouseDoubleClick="Button_MouseDoubleClick" >Click me</Button>
    
    private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        if(e.ChangedButton == MouseButton.Right)
        {
        }
        e.Handled = true;
    }
    

    or for mouse down

    <Button MouseDown="Button_MouseDown" >Click me</Button>
    
    private void Button_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if(e.ChangedButton == MouseButton.Right)
        {
        }
        e.Handled = true;
    }