1

我的意图是捕获特定控件的鼠标事件,但鼠标捕获立即丢失

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);吗?

4

2 回答 2

1

对我来说,代码有效。但是设置 b 变量意味着您正在设置断点。我会用 Debug 语句替换它们以开始..

于 2013-04-19T16:09:52.563 回答
1

你也应该设置

e.Handled = true;

在您的Button_Click事件处理中,使其在任何地方都能正常工作。

于 2019-05-16T15:45:11.813 回答