2010-03-09 396 views

回答

25

的公共變量按鈕 定義上,鼠標懸停事件看一看GetChildAtPoint。如果控件包含在容器中,則必須執行一些額外的工作,請參見Control.PointToClient

+0

就是這樣!謝謝! – Poma

+1

對於Control.PointToClient +1 –

1

怎麼樣,在每個指定發送按鈕,按鈕式

+0

其實我不是按鈕,它是第三方插件;) – Poma

1

你可以做多種方式:

  1. MouseEnter活動窗體的控件。 「發件人」參數會告訴你什麼控制引發了事件。

  2. 使用System.Windows.Forms.Cursor.Location獲取光標位置,並使用Form.PointToClient()將其映射到表單的座標。然後您可以將該點傳遞給Form.GetChildAtPoint()以找到該點下的控件。

安德魯

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

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

這會給你在光標下的控制權。