I need a way of detecting when the cursor enters or leaves the form. Form.MouseEnter/MouseLeave doesn't work when controls fill the form, so I will also have to subscribe to MouseEnter event of the controls (e.g. panels on the form). Any other way of tracking form cursor entry/exit globally?
Asked
Active
Viewed 3,375 times
2
-
2you will find your [answer](http://stackoverflow.com/questions/986529/how-to-detect-if-the-mouse-is-inside-the-whole-form-and-child-controls-in-c) – David Mar 08 '12 at 13:53
-
Another way would be switch to WPF that address this specific problem with routed events. – Ignacio Soler Garcia Mar 08 '12 at 13:58
-
A simple 200 msec Timer, Mouse.Position and the form's PointToClient() method is often an effective way. IMessageFilter works too. – Hans Passant Mar 08 '12 at 14:29
2 Answers
4
You can try this :
private void Form3_Load(object sender, EventArgs e)
{
MouseDetector m = new MouseDetector();
m.MouseMove += new MouseDetector.MouseMoveDLG(m_MouseMove);
}
void m_MouseMove(object sender, Point p)
{
Point pt = this.PointToClient(p);
this.Text = (this.ClientSize.Width >= pt.X &&
this.ClientSize.Height >= pt.Y &&
pt.X > 0 && pt.Y > 0)?"In":"Out";
}
The MouseDetector class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
class MouseDetector
{
#region APIs
[DllImport("gdi32")]
public static extern uint GetPixel(IntPtr hDC, int XPos, int YPos);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetCursorPos(out POINT pt);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
#endregion
Timer tm = new Timer() {Interval = 10};
public delegate void MouseMoveDLG(object sender, Point p);
public event MouseMoveDLG MouseMove;
public MouseDetector()
{
tm.Tick += new EventHandler(tm_Tick); tm.Start();
}
void tm_Tick(object sender, EventArgs e)
{
POINT p;
GetCursorPos(out p);
if (MouseMove != null) MouseMove(this, new Point(p.X,p.Y));
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
}
}

LarsTech
- 80,625
- 14
- 153
- 225

Amen Ayach
- 4,288
- 1
- 23
- 23
1
You can do it with win32 like in this answer: How to detect if the mouse is inside the whole form and child controls in C#?
Or you could just hook up all the top level controls in OnLoad of the form:
foreach (Control control in this.Controls)
control.MouseEnter += new EventHandler(form_MouseEnter);
-
1Regarding your second option: You would also have to worry about child controls having child controls (who also have child controls, who also have...). I wouldn't recommend that implementation. – ean5533 Mar 08 '12 at 14:26