如何检查目标是否未在WPF中命中

时间:2014-09-13 14:56:33

标签: c# wpf hittest

我使用下面的代码查看点击鼠标右键的时间,是否达到了目标(Drawing)。

现在如果鼠标击中目标,将显示一条消息,说明我们击中了目标。

但是,我在哪里可以显示目标命中的消息? VisualTreeHelper.HitTest()似乎没有返回表示目标被击中的值。

private void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    var x = MousePos.RightDown.X;
    var y = MousePos.RightDown.Y;

    var hitRect = new Rect(x - 2, y - 2, 4, 4);
    var geom = new RectangleGeometry(hitRect);

    VisualTreeHelper.HitTest(Drawing, 
                             null, 
                             MyCallback, 
                             new GeometryHitTestParameters(geom));

    // Where should I put the MessageBox.Show("You did not hit the target");
    // If I put it here it is displayed anyway

}

private HitTestResultBehavior MyCallback(HitTestResult result)
{
    MessageBox.Show("You hit the target");
    return HitTestResultBehavior.Stop;
}

2 个答案:

答案 0 :(得分:2)

使用某个班级 标志来指示点击是否成功 。从MyCallback将标志设置为true,并根据该标志显示消息。

bool isTargetHit;    
private void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    isTargetHit = false;

    .......
    VisualTreeHelper.HitTest(Drawing, 
                             null, 
                             MyCallback, 
                             new GeometryHitTestParameters(geom));

    if(isTargetHit)
    {
        MessageBox.Show("You hit the target");
    }
    else
    {
        MessageBox.Show("You did not hit the target");
    } 
}

private HitTestResultBehavior MyCallback(HitTestResult result)
{
    isTargetHit = true;
    return HitTestResultBehavior.Stop;
}

答案 1 :(得分:2)

除了Rohit所说的,你还可以使用本地标志和匿名回调方法,如下所示:

private void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    bool isTargetHit = false;

    VisualTreeHelper.HitTest(
        Drawing,
        null,
        r =>
        {
            isTargetHit = true;
            return HitTestResultBehavior.Stop;
        },
        new GeometryHitTestParameters(geom));

    if (isTargetHit)
    {
        MessageBox.Show("You hit the target");
    }
    else
    {
        MessageBox.Show("You did not hit the target");
    }
}