Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MouseHover/MouseLeave event on the whole entire window

I have Form subclass with handlers for MouseHover and MouseLeave. When the pointer is on the background of the window, the events work fine, but when the pointer moves onto a control inside the window, it causes a MouseLeave event.

Is there anyway to have an event covering the whole window.

(.NET 2.0, Visual Studio 2005, Windows XP.)

like image 850
billpg Avatar asked Jan 06 '10 18:01

billpg


3 Answers

Ovveride the MouseLeave event to not trigger so long as the mouse enters a child control

    protected override void OnMouseLeave(EventArgs e)
    {
        if (this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))
            return;
        else
        {
            base.OnMouseLeave(e);
        }
    }
like image 113
Ryan Avatar answered Oct 18 '22 10:10

Ryan


When the mouse leave event is fired one option is to check for the current position of the pointer and see if it within the form area. I am not sure whether a better option is available.

Edit: We have a similar question which might be of interest to you. How to detect if the mouse is inside the whole form and child controls in C#?

like image 20
Shoban Avatar answered Oct 18 '22 11:10

Shoban


There is no good way to make MouseLeave reliable for a container control. Punt this problem with a timer:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        timer1.Interval = 200;
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Enabled = true;
    }

    private bool mEntered;

    void timer1_Tick(object sender, EventArgs e) {
        Point pos = this.PointToClient(Cursor.Position);
        bool entered = this.ClientRectangle.Contains(pos);
        if (entered != mEntered) {
            mEntered = entered;
            if (!entered) {
                // Do your leave stuff
                //...
            }
        }
    }
}
like image 24
Hans Passant Avatar answered Oct 18 '22 11:10

Hans Passant