Mouse Leave event on Windows Form [duplicate]
Asked Answered
D

3

6

I've set the 'mouse leave' event on a windows form and I want to hide the form when the mouse leaves the visible area.

But here is where I am facing a problem. Even when I move the mouse to a button on the same form, it calls the 'mouse leave' event, which makes this form invisible.

It means I've got to prevent the event triggering when moving the mouse to the button. But how? Any other approach?

Denationalize answered 18/10, 2011 at 17:19 Comment(2)
The problem with mouse events on the form is that none of them will fire if you have any control covering the entire form client area (e.g. docked). So if you use the MouseMove event as MusiGenesis suggests, just be aware of that.Sibilant
There's no clean way to do this, you'll need a Timer. Hide the form when this.Bounds.Contains(Cursor.Position) is false. Getting the form to show again is going to be pretty difficult :)Woosley
A
1

There is no simple way to do it. One way could be to check all the controls inside the Form and if mouse is not over any of them this means mouse is outside the Form

Another way could be to check inside mouse leave event whether mouse is inside the window boundary or not

Aymara answered 18/10, 2011 at 17:25 Comment(4)
It will take too much effort. Isn't it?Denationalize
Yes, as I said there is no simple way to do it. The first option can be used if you have a small number of controls inside Form otherwise go for the second optionAymara
You can reach all controls and subcontrols via the Controls property (msdn.microsoft.com/en-us/library/…). You could walk this control tree upon each MouseLeave if the Form is not too big/complex.Kuehn
@HarisHasan below is a better solution, Hassan (remember me? :)) #424228Epsomite
L
1

it's very simple...add this:

protected override void OnMouseLeave(EventArgs e)
{

    if(this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))
         return;
    else
    {
        base.OnMouseLeave(e);
    }
}
Lactase answered 9/5, 2016 at 15:42 Comment(0)
B
0
// On the form's MouseLeave event, please checking for mouse position is not in each control's client area.
private void TheForm_MouseLeave(object sender, EventArgs e)
{
    bool mouse_on_control = false;
    foreach (var c in Controls)
        mouse_on_control |= c.RectangleToScreen(c.ClientRectangle).Contains(Cursor.Position);
    if (!mouse_on_control)
        Close();
}

// And in addition, if any control inside has its client area overlapping the form's client area at any border, 
// please also checking if mouse position is outside the form's client area on the control's MouseLeave event.
private void ControlOverlappedTheFormsBorder_MouseLeave(object sender, EventArgs e)
{
    if (!RectangleToScreen(ClientRectangle).Contains(Cursor.Position))
        Close();
}
Bellyache answered 1/6, 2014 at 13:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.