WinForms:检测光标何时进入/离开窗体或其控件

本文关键字:窗体 离开 控件 检测 光标 何时进 WinForms | 更新日期: 2023-09-27 18:27:19

我需要一种检测光标何时进入或离开窗体的方法。当控件填充窗体时,form.MouseEnter/MouseLeave不起作用,所以我还必须订阅控件的MouseEnter事件(例如窗体上的面板)。是否有其他方法可以全局跟踪表单光标的进入/退出?

WinForms:检测光标何时进入/离开窗体或其控件

你可以试试这个:

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

鼠标检测器类:

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

您可以使用win32来完成,如下所示:如何检测鼠标是否在C#中的整个窗体和子控件中?

或者你可以在OnLoad中连接所有的顶级控件:

     foreach (Control control in this.Controls)
            control.MouseEnter += new EventHandler(form_MouseEnter);