当前位置:  开发笔记 > 编程语言 > 正文

如何检测鼠标何时离开表格?

如何解决《如何检测鼠标何时离开表格?》经验,为你挑选了1个好方法。

我有一个表格,上面有很多控件.如何检测鼠标何时离开表格?我已尝试为每个控件和表单连接一个MouseLeave事件,但这不起作用,因为当鼠标经过控件时,这些事件会一直触发.有没有一种实际有效的方法.



1> Eren Aygunes..:

你应该听:

MouseLeave窗体的所有控件的事件

表单的MouseLeave事件

只需将您的侦听器链接到一个函数,该函数检查光标是否在表单客户端中.

试试这个:

    protected override void OnControlAdded(ControlEventArgs e)
    {
        SubscribeEvents(e.Control);
        base.OnControlAdded(e);
    }

    protected override void OnControlRemoved(ControlEventArgs e)
    {
        UnsubscribeEvents(e.Control);
        base.OnControlRemoved(e);
    }

    private void SubscribeEvents(Control control)
    {
        control.MouseLeave += new EventHandler(control_MouseLeave);
        control.ControlAdded += new ControlEventHandler(control_ControlAdded);
        control.ControlRemoved += new ControlEventHandler(control_ControlRemoved);

        foreach (Control innerControl in control.Controls)
        {
            SubscribeEvents(innerControl);
        }
    }

    private void UnsubscribeEvents(Control control)
    {
        control.MouseLeave -= new EventHandler(control_MouseLeave);
        control.ControlAdded -= new ControlEventHandler(control_ControlAdded);
        control.ControlRemoved -= new ControlEventHandler(control_ControlRemoved);

        foreach (Control innerControl in control.Controls)
        {
            UnsubscribeEvents(innerControl);
        }
    }

    private void control_ControlAdded(object sender, ControlEventArgs e)
    {
        SubscribeEvents(e.Control);
    }

    private void control_ControlRemoved(object sender, ControlEventArgs e)
    {
        UnsubscribeEvents(e.Control);
    }

    protected override void OnMouseLeave(EventArgs e)
    {
        CheckMouseLeave();
        base.OnMouseLeave(e);
    }

    private void control_MouseLeave(object sender, EventArgs e)
    {
        CheckMouseLeave();
    }

    private void CheckMouseLeave()
    {
        Point pt = PointToClient(Cursor.Position);

        if (ClientRectangle.Contains(pt) == false)
        {
            OnMouseLeftFrom();
        }
    }

    private void OnMouseLeftFrom()
    {
        Console.WriteLine("Mouse left the form");
    }

推荐阅读
路人甲
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有