WinForms: Detect when cursor enters/leaves the form or its controls

馋奶兔 提交于 2019-12-12 18:34:02

问题


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


来源:https://stackoverflow.com/questions/9618657/winforms-detect-when-cursor-enters-leaves-the-form-or-its-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!