我的目的是捕获特定控件的鼠标事件,但鼠标捕获会立即丢失
XAML
<Window x:Class="TryMouseCapture.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label x:Name="lbl" BorderBrush="Black" BorderThickness="2" GotMouseCapture="lbl_GotMouseCapture" IsEnabled="True" LostMouseCapture="lbl_LostMouseCapture" MouseLeftButtonDown="lbl_MouseLeftButtonDown">Mouse captured here</Label>
<Label Grid.Row="1" BorderBrush="Red" BorderThickness="2">Click here</Label>
<Button Grid.Row="2" Click="Button_Click">Capture Mouse in the first label</Button>
</Grid>
</Window>
背后的代码
private void lbl_GotMouseCapture(object sender, MouseEventArgs e)
{
Label label = (Label)sender;
var b = label.IsMouseCaptured;
}
private void lbl_LostMouseCapture(object sender, MouseEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var b = Mouse.Capture(lbl);
}
private void lbl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}
因此,点击该按钮后,系统会调用lbl_GotMouseCapture
,然后立即lbl_LostMouseCapture
。
除了打电话给Mouse.Capture(lbl);
之外还有别的事可做吗?
答案 0 :(得分:1)
对我来说代码有效。但设置b变量意味着您正在设置断点。我会用Debug语句替换它们以...开头。
答案 1 :(得分:0)
您还应该设置
e.Handled = true;
在您的Button_Click
事件处理中,使其可以在任何地方使用。