Skip to main content
 首页 » 编程设计

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

2024年02月06日11bonelee

我正在使用下面的代码来查看何时单击鼠标右键,它是否击中了目标(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; 
} 

请您参考如下方法:

有一些类级别的标志来指示命中是否成功。从 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; 
}