如何在鼠标光标下进行控制?

时间:2010-03-09 17:28:36

标签: c# winforms mouse

我有几个按钮的表单,我想知道现在光标下面有什么按钮。

P.S。也许这是重复的,但我找不到这个问题的答案。

5 个答案:

答案 0 :(得分:27)

看看GetChildAtPoint。如果控件包含在容器中,则必须执行一些额外的工作,请参阅Control.PointToClient

答案 1 :(得分:18)

对于大多数人来说,GetChildAtPointPointToClient可能是第一个想法。我也先用它。但是,GetChildAtPoint无法使用不可见或重叠的控件正常工作。这是一个运行良好的代码,它可以管理这些情况。

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

public static Control FindControlAtPoint(Control container, Point pos)
{
    Control child;
    foreach (Control c in container.Controls)
    {
        if (c.Visible && c.Bounds.Contains(pos))
        {
            child = FindControlAtPoint(c, new Point(pos.X - c.Left, pos.Y - c.Top));
            if (child == null) return c;
            else return child;
        }
    }
    return null;
}

public static Control FindControlAtCursor(Form form)
{
    Point pos = Cursor.Position;
    if (form.Bounds.Contains(pos))
        return FindControlAtPoint(form, form.PointToClient(pos));
    return null;
}

这将为您提供光标下的控制权。

答案 2 :(得分:4)

// This getYoungestChildUnderMouse(Control) method will recursively navigate a       
// control tree and return the deepest non-container control found under the cursor.
// It will return null if there is no control under the mouse (the mouse is off the
// form, or in an empty area of the form).
// For example, this statement would output the name of the control under the mouse
// pointer (assuming it is in some method of Windows.Form class):
// 
// Console.Writeline(ControlNavigatorHelper.getYoungestChildUnderMouseControl(this).Name);


    public class ControlNavigationHelper
    {
        public static Control getYoungestChildUnderMouse(Control topControl)
        {
            return ControlNavigationHelper.getYoungestChildAtDesktopPoint(topControl, System.Windows.Forms.Cursor.Position);
        }

        private static Control getYoungestChildAtDesktopPoint(Control topControl, System.Drawing.Point desktopPoint)
        {
            Control foundControl = topControl.GetChildAtPoint(topControl.PointToClient(desktopPoint));
            if ((foundControl != null) && (foundControl.HasChildren))
                return getYoungestChildAtDesktopPoint(foundControl, desktopPoint);
            else
                return foundControl;
        }
    }

答案 3 :(得分:2)

你可以通过多种方式实现:

  1. 收听表单控件的MouseEnter事件。 “sender”参数将告诉您引发事件的控件。

  2. 使用System.Windows.Forms.Cursor.Location获取光标位置,并使用Form.PointToClient()将其映射到表单的坐标。然后,您可以将该点传递给Form.GetChildAtPoint()以查找该点下的控件。

  3. 安德鲁

答案 4 :(得分:1)

如何在每个按钮中定义on-Mouse-over事件 它将发件人按钮分配给按钮类型的公共变量