什么是说,如果鼠标在一个窗体或不是最好的方法是什么? [英] What's the best way to tell if the mouse is over a form or not?

查看:115
本文介绍了什么是说,如果鼠标在一个窗体或不是最好的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通了,<一个href="http://stackoverflow.com/questions/2866936/how-can-i-add-an-event-handler-to-an-event-by-name">how捕捉鼠标点击的整个形式,但这种方法并不能很好的转化为的MouseEnter 鼠标离开。我的窗体布局从许多面板由 TableLayoutPanels 所以没有全方位的控制,我可以监视事件,明明一个鼠标离开事件按钮并不意味着光标离开了整个表单。有没有人想出了一个好办法来解决这个问题?

I figured out how to capture mouse clicks over the entire form, but this method doesn't translate well for MouseEnter and MouseLeave. My form layout is made up from many Panels and TableLayoutPanels so there's no all-encompassing control I can monitor events for, and obviously a MouseLeave event for a button doesn't mean the cursor left the entire form. Has anyone figured out a good way to get around this?

推荐答案

正如有人指出的这里有可能使用调用SetWindowsHookEx()或只是挂钩MouseMove事件到表单中的所有控件。后者对我的作品的罚款。唯一的缺点是,如果你添加/删除控件在运行时可能需要另一种解决方案。

As someone pointed out here it's possible to use SetWindowsHookEx() or just hook up MouseMove event onto all controls in the form. The latter works for me fine. The only downside is if you add/remove controls at runtime you might need another solution.

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

    }
}

这篇关于什么是说,如果鼠标在一个窗体或不是最好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆