2011-09-22 56 views
1

我的表單層次結構是這樣的:GetChildAtPoint方法返回錯誤的控制

Form -> TableLayoutOne -> TableLayoutTwo -> Panel -> ListBox 

在ListBox的MouseMove事件,我有這樣的代碼:

Point cursosPosition2 = PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y)); 
    Control crp = this.GetChildAtPoint(cursosPosition2); 
    if (crp != null) 
     MessageBox.Show(crp.Name); 

MessageBox的是顯示我是「TableLayoutOne」,但我期望它向我展示「ListBox」。我的代碼中哪裏出錯了?謝謝。

回答

5

GetChildFromPoint()方法使用本地ChildWindowFromPointEx()方法,其文檔狀態:

決定,如果有的話,屬於 指定的父窗口的子窗口中包含指定點。函數 可忽略不可見,禁用和透明的子窗口。 搜索 僅限於直接子窗口。孫子和更深的 後代不搜索。

注意粗體文本:方法不能得到你想要的。

從理論上講,你可以在控制返回調用GetChildFromPoint()直到你得到null

Control crp = this.GetChildAtPoint(cursosPosition2); 
Control lastCrp = crp; 

while (crp != null) 
{ 
    lastCrp = crp; 
    crp = crp.GetChildAtPoint(cursorPosition2); 
} 

然後你就會知道,lastCrp在那個位置最低的後裔。

+0

當然!感謝您的信息...你有其他想法如何得到它?也許閱讀Cursor位置並檢查它是否在ListBox的位置內? – Bohn

+1

查看我的更新;您可以繼續在返回的控件上調用'GetChildAtPoint()'以在層次結構中進一步深入。你也可以在每個階段自由地檢查控制的類型,所以如果你找到了你想要的東西,你就可以紓困。 – dlev