WinForms: Detect when cursor enters/leaves the for

2019-07-11 01:50发布

问题:

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?

回答1:

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;
    }
  }
}


回答2:

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);