简体   繁体   English

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

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

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 (eg panels on the form). 当控件填充表单时,Form.MouseEnter / MouseLeave不起作用,因此我还必须订阅控件的MouseEnter事件(例如,表单上的面板)。 Any other way of tracking form cursor entry/exit globally? 是否有其他方法来全局跟踪表单光标的输入/退出?

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 : MouseDetector类:

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

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#? 您可以使用win32做到这一点,例如此答案: 如何检测鼠标是否在C#的整个窗体和子控件中?

Or you could just hook up all the top level controls in OnLoad of the form: 或者,您也可以仅挂接表单的OnLoad中的所有顶级控件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM