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.