开发者

In MouseMove event, how to determine if cursor is w/i certain distance of an edge?

When the user moves the mouse over an object, I'm trying to do some hit-testing in my MouseMove event handler to detect when the cursor is w/i a certain distance from an edge of the object. I suspect that in the MouseEnter handler I need to store the location of the object, then in MouseMove compare

e.GetPosition(this)

to the location +/- dimensions.

How do I get the position of an object relative to the same root that e.GetPosition(this) returns its Point? e.GetPosition(this) returns a point relative to this; how can I determine if point.x is 1 pixe开发者_如何学Pythonl or 12 pixels from an edge of the containing object. The goal is know if the mouse is w/i a certain distance of an object's edge.

Thanks for any advice.


The MouseEventArgs GetPosition() function returns the position relative to the framework element that's passed to it (that is, the FrameworkElement in question can be this, but doesn't have to be). So you could write something like:

bool isNearTarget=false;
FrameworkElement targetObject;
double nearDistance;

Point location=e.GetPosition(targetObject);
if((location.X>(-nearDistance)) && (location.X<nearDistance) ||
   (location.Y>(-nearDistance)) && (location.Y<nearDistance) ||
   (location.X>(targetObject.Width - nearDistance)) && 
       (location.X<targetObject.Width + nearDistance)) ||
   (location.Y>(targetObject.Height - nearDistance)) && 
       (location.Y<targetObject.Height + nearDistance)))
 {   
    isNearTarget=true;
 {


I was making it too complicated...

MouseEnter()
{
        double txtBoxLeft = Canvas.GetLeft(sidesStackPanel);
        double txtBoxRight = txtBoxLeft + sidesStackPanel.ActualWidth;

        Point p = e.GetPosition(null);
        _leftGully = txtBoxLeft + _gullyWidth;
        _rightGully = txtBoxRight - _gullyWidth;
}
MouseMove()
{
    StackPanel sp = sender as StackPanel;

    if (null != sp)
    {
        Point p = e.GetPosition(sp);
        if (p.X <= _leftGully)
        {
            System.Diagnostics.Debug.WriteLine("  Move: In left gully");
        }
        else if (p.X >= _rightGully)
        {
            System.Diagnostics.Debug.WriteLine("  Move: In right gully");
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜