如何在wpf C#中检查鼠标按钮是左还是右?

时间:2017-01-18 11:30:50

标签: c# wpf wpf-controls mouse

我尝试使用此代码实际上只创建了Click="button_Click"上的一个Eventhandler。

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> 

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

2 个答案:

答案 0 :(得分:7)

Click仅适用于最有限的交互,如果您使用更高级的鼠标事件,则会获得MouseButtonEventArgs,它会为您提供有关该事件的所有详细信息。

原因是Click不是鼠标事件,您也可以通过触控,触控笔触发它,您甚至可以通过按下Return键来触发它,同时突出显示

所以请尝试使用MouseDown,MouseUp或DoubleClick

例如

name
div

或鼠标按下

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

答案 1 :(得分:1)

为左右鼠标分别设置单独的事件处理程序总是更好。如果您需要按照单击的按钮工作。以下是我的方法。

<Button MouseLeftButtonDown="Button_MouseLeftButtonDown" MouseRightButtonDown="Button_MouseRightButtonDown"></Button>

下面是代码。

private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{

}

private void Button_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{

}

如果您想获得导致该事件的按钮,您可以查看e.OriginalSource属性。