判断鼠标是否位于表单上方的最佳方法是什么?

dlr*_*as2 5 .net c# mouseover winforms

我想出了如何捕获整个表单上的鼠标点击,但此方法不能很好地转换为MouseEnterMouseLeave。我的表单布局由许多组成PanelsTableLayoutPanels因此没有可以监视事件的包罗万象的控件,显然MouseLeave按钮的事件并不意味着光标离开整个表单。有没有人想出一个好方法来解决这个问题?

Sla*_*aGu 0

正如有人指出的,可以使用 SetWindowsHookEx() 或将 MouseMove 事件挂接到表单中的所有控件上。后者对我来说效果很好。唯一的缺点是,如果您在运行时添加/删除控件,您可能需要另一个解决方案。

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsForms_MouseEvents
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            MouseMove += OnMouseMove;
            MouseLeave += OnMouseLeave;

            HookMouseMove(this.Controls);
        }

        private void HookMouseMove(Control.ControlCollection ctls)
        {
            foreach (Control ctl in ctls)
            {
                ctl.MouseMove += OnMouseMove;
                HookMouseMove(ctl.Controls);
            }
        }

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            BackColor = Color.Plum;

            Control ctl = sender as Control;
            if (ctl != null)
            {
                // Map mouse coordinate to form
                Point loc = this.PointToClient(ctl.PointToScreen(e.Location));
                Console.WriteLine("Mouse at {0},{1}", loc.X, loc.Y);
            }
        }

        private void OnMouseLeave(object sender, EventArgs e)
        {
            BackColor = Color.Gray;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)