如何在 wpf C# 中检查鼠标按钮是向左还是向右?
我正在尝试这段代码,实际上我只创建了一个位于 Click="button_Click"
上的 Eventhandler.
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>
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;
}
}
Click 仅设计用于最有限的交互,如果您使用更高级的鼠标事件,您将获得一个 MouseButtonEventArgs,它为您提供有关该事件的所有详细信息.
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.
这样做的原因是 Click 不是鼠标事件,您也可以通过触摸、手写笔触发它,您甚至可以通过在突出显示时按 Return 键来触发它
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
所以试试 MouseDown、MouseUp 或 DoubleClick
so try MouseDown, MouseUp or DoubleClick instead
例如
<Button MouseDoubleClick="Button_MouseDoubleClick" >Click me</Button>
private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if(e.ChangedButton == MouseButton.Right)
{
}
e.Handled = true;
}
或鼠标按下
<Button MouseDown="Button_MouseDown" >Click me</Button>
private void Button_MouseDown(object sender, MouseButtonEventArgs e)
{
if(e.ChangedButton == MouseButton.Right)
{
}
e.Handled = true;
}