的WinForms:检测时,指针进入/离开的形式或其控制指针、或其、形式、WinForms

2023-09-06 04:59:38 作者:我在上帝心中

我需要的当光标进入或离开的形式检测的方式。当控件填写表格Form.MouseEnter /鼠标离开是不行的,所以我也必须订阅控制MouseEnter事件(如板的形式)。全球范围内跟踪表指针进入/退出的任何其他方式?

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?

推荐答案

您可以试试这个:

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

在MouseDetector类:

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