Search code examples
c#.neteventsmouseleave

MouseLeave eventhandler is too slow


I'm using the MouseLeave event to check if the user left my form and to close my window, but using this.MouseLeave += new System.EventHandler(this.InvisibleForm_Leave); is too slow, only if I'm going to leave my form slowly the event is fired, moving it in a normal way / a little bit faster I don't get a leave event.

Therefore I tried to check on my own if the mouse left my form or not:

private void checkPos()
    {
        Rectangle rec = this.Bounds;
        while (true)
        {
            Point point = new Point(Cursor.Position.X, Cursor.Position.Y);
            if (!rec.Contains(point))
            {
                Console.WriteLine("leaving");
                this.Close();                    
            }
            Thread.Sleep(100);
        }
    }

started in a own thread after creating the form:

public MyForm()
    {
        InitializeComponent();
        Thread m_mouseListenerThread = new Thread(new ThreadStart(this.checkPos));
        m_mouseListenerThread.Start();            
    }

But with this I have more or less the same problem, leaving the area still returns true after checking it with rec.Contains(point) only after a second he is going to execute the if code, but sometimes he's getting it in an instant.

The second problem with this is that I'm getting a thread exception in the this.Close(); line in the checkPost() method:

Cross-thread operation not valid: Control 'MyForm' accessed from a thread other than the thread it was created on.

Now I don't really know how to implement the mouse leaving part in another way.


Solution

    1. For the mouse leaving part, I am not quite sure. Maybe you can try to handle that by MouseMove event?
    2. For the invalid cross-thread operation issue, you simply cannot access a control which is owned by another thread (it's the UI thread in your case). Use Control.BeginInvoke or Control.Invoke instead.