Determine if the mouse is outside the form

K

kurotsuke

I need to detect if the mouse get out of the window form.
I'm displaying a form with border and titlebar with a panel that
covers all the surface of the form, so unfortunately the MouseLeave
event is of no use.

Probably it should get the form rectangle and see if the mousepointer
is contained inside.

How can I do that? (I'm working in C#)
Thanks.
 
C

ClayB [Syncfusion]

I think code like this may do it.

// this is the form
Point pt = Control.MousePosition;
Rectangle rect = this.RectangleToScreen(new Rectangle(0, 0, this.Width,
this.Height));
if(!rect.Contains(pt))
{
//mouse outside the form
}

===========
Clay Burch, .NET MVP

Visit www.syncfusion.com for the coolest tools
 
K

kurotsuke

I think code like this may do it.

// this is the form
Point pt = Control.MousePosition;
Rectangle rect = this.RectangleToScreen(new Rectangle(0, 0, this.Width,
this.Height));
if(!rect.Contains(pt))
{
//mouse outside the form
}

===========
Clay Burch, .NET MVP

Visit www.syncfusion.com for the coolest tools

Thank a lot Clay. This looks good to me but what event should I watch?
I cannot use mouseMove when the pointer is outside the form or inside
a panel.
Thanks again
 
K

kurotsuke

I made a slight modification at your code (when the mouse pointer was
in the title bar it was reported incorrectly as outside)
This fixes the problem

// this is the form
Point pt = Control.MousePosition;
Rectangle rect = this.Bounds;

if(!rect.Contains(pt))
{
//mouse outside the form
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top