c# - 我可以在 Mouse.Capture() 处于事件状态时获得 MouseLeave 事件吗?

标签 c# wpf mouse capture mouseleave

我有一个按钮。在 Button.MouseRightButtonDown 上,我调用了 Mouse.Capture(button),因为我想检测是否有人在 Button 之外释放了右键单击。

我还注册了一个 Button.MouseLeave 事件。如果有人右键单击-将鼠标拖离按钮,我希望触发此事件。

不幸的是,Mouse.Capture 似乎以某种方式阻止了 MouseLeave 的发生。

有谁知道解决方法,或者可以指出我哪里出错了?

(顺便说一句,如果有人对我这样做的目的感到好奇,请参阅 my other question。)

最佳答案

捕获鼠标后,您可以使用 MouseMove 和 HitTest 来确定鼠标是在您的元素内还是在其他元素内。

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    if (this.IsMouseCaptured)
    {
        HitTestResult ht = VisualTreeHelper.HitTest(this, e.GetPosition(this));
        if (ht != null)
        {
            DependencyObject current = ht.VisualHit;
            while (current != this && current != null)
            {
                current = VisualTreeHelper.GetParent(current);
            }

            if (current == this)
            {
                Debug.WriteLine("Inside");
                return;
            }
        }

        Debug.WriteLine("Outside");
    }
}

下面的代码可以用来避免树遍历:

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    if (this.IsMouseCaptured)
    {
        bool isInside = false;

        VisualTreeHelper.HitTest(
            this,
            d =>
            {
                if (d == this)
                {
                    isInside = true;
                }

                return HitTestFilterBehavior.Stop;
            },
            ht => HitTestResultBehavior.Stop,
            new PointHitTestParameters(e.GetPosition(this)));

        if (isInside)
        {
            Debug.WriteLine("Inside");
        }
        else
        {
            Debug.WriteLine("Outside");
        }
    }
}

关于c# - 我可以在 Mouse.Capture() 处于事件状态时获得 MouseLeave 事件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961050/

相关文章:

c# - 从父 View 模型 wpf mvvm 关闭子窗口

wpf - ItemsControl ItemTemplate 绑定(bind)

c# - 在 WPF 的代码隐藏中更改字体样式

javascript - 如何禁用除单击之外的所有鼠标事件?

java - java awt中设置光标位置

c# - 可从 C# 中使用的基准库

c# - C#中的方法参数赋值

c# - 在 .Net 中创建提醒服务的最佳方式是什么?

c# - 暂停窗口,如 MessageBox.Show()

c - C 中的简单 NCURSES 鼠标处理