如何在鼠标光标下获得控制权?

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

PS也许它重复,但我找不到这个问题的答案。

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

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

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

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

你可以通过多种方式实现这一目标:

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

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

安德鲁

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