c#-判断鼠标是否在表单上方的最佳方法是什么?

我在整个表单中算出了how to capture mouse clicks,但是对于MouseEnter和MouseLeave来说,这种方法不能很好地转换.我的表单布局由许多Panels和TableLayoutPanels组成,因此没有可以监视事件的所有控件,显然,按钮的MouseLeave事件并不意味着光标离开了整个表单.有谁找到解决这个问题的好方法?

解决方法:

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

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

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

            MouseMove += onm ouseMove;
            MouseLeave += onm ouseLeave;

            HookMouseMove(this.Controls);
        }

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

        private void onm ouseMove(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 onm ouseLeave(object sender, EventArgs e)
        {
            BackColor = Color.Gray;
        }

    }
}
上一篇:C#-WinForms鼠标捕获


下一篇:c#-滚动到WebBrowser控件的顶部