2012-01-05 149 views
2

如何檢查一個對象(在這種情況下,我的對象是一個ButtonBox)是否存在於一個GroupBox中,但在一個確切的位置。如何檢查一個GroupBox中是否存在對象 - VB.NET

事情是這樣的:

If Groupbox1.NameOfButtonBox.location(40,190) exists then 
     Do my code 
end if 

我知道的語法是完全錯誤的,但它只是一個例子

+2

*不要*測試控制的位置屬性。當窗體在具有不同視頻DPI設置的機器上自動縮放時,控件將四處移動。爲什麼你想要做到這一點,否則無法猜測。 – 2012-01-05 22:05:12

+0

那麼讓我解釋一下。我有一個Groupbox內有4個按鈕的表單,每個按鈕都有自己的背景圖像。我想要做的是檢查是否有任何按鈕存在於該確切位置(每個按鈕都有其自己的確切位置),如果沒有,則會在該位置放置一個新按鈕,直到Groupbox有4個按鈕(因此它將有4個位置)然後一個新的Groupbox將被創建,如果「舊」已經有4個按鈕等等。用戶將爲每個新按鈕提供名稱。 – 2012-01-05 23:44:28

+0

好吧,只要跟蹤你做了什麼,所以你不必找到困難的方式。當你創建一個按鈕時,也將它添加到你存儲在類的字段中的List(Of Button)。如果您需要多個組框,則列表(Of List(Of Button))。 – 2012-01-06 00:19:48

回答

1

爲了使用這個按鈕類型而不是特定的按鈕的實例,您將需要檢查找到的控件的類型。你還需要確保那裏有一個控制。這是一個函數,它將檢查一個groupbox是否在給定的座標中包含一個按鈕。

Private Function ButtonExists(ByVal group As GroupBox, ByVal x As Integer, ByVal y As Integer) As Boolean 

    'No sense checking if there isn't a group box 
    If group Is Nothing Then 
     Return False 
    End If 

    'Find the control at the given point 
    Dim ctrl As Control = group.GetChildAtPoint(New Point(x, y)) 

    'If there is a control at that point check to see if it's a button 
    If ctrl IsNot Nothing AndAlso TypeOf (ctrl) Is Button Then 
     Return True 
    End If 

    Return False 
End Function 
+0

感謝@Briddums代碼正在工作。 現在我必須爲每個Button動態設置BackgroundImage。 我有4個按鈕,每個按鈕都被命名爲「Button1」,「Button2」等。 所以基本上我有這樣的事情: 'n = 1時至4 DO 按鈕和n.BackgroundImage = Image.FromFile(XXXXXXX) next' 再次聲明,我有問題的按鈕類型,而不是因爲具有一個靜態的按鈕實例,我想要一個動態的實例。 你能幫我這個嗎? 謝謝 – 2012-01-06 23:07:10

+0

@EricFernandez最簡單的方法是遍歷groupbox中的按鈕控件。對於Groupbox1.Controls中的每個控件作爲控件如果Typeof(ctrl)是Button然後ctype(ctrl,Button).BackgroundImage = Image.FromFile(xxx) – briddums 2012-01-09 14:35:20

+0

謝謝@briddums。它工作正常:D – 2012-01-09 18:45:03

0

退房GetChildAtPoint:

Dim ctrl As Control = GroupBox1.GetChildAtPoint(New Point(147, 96)) 
If TypeOf ctrl Is Button Then 
    Dim btn As Button = DirectCast(ctrl, Button) 
    'Do your code 
End If 

MSDN: Control.GetChildAtPoint Method

+0

感謝邁克的代碼,如果工作,部分... 那麼問題是,我想檢查是否有任何ButtonBox在該位置,所以我不會在IF語句中寫入特定的buttonbox名稱。例如: Dim ctrl As Control = Me.GetChildAtPoint(New Point(147, 96)) If ANYButtonBox.Equals(ctrl) Then 'Do your code End If 2012-01-05 23:08:07

+0

更新了示例代碼,以更準確地反映您正在嘗試執行的操作。 – 2012-01-06 13:20:25

相關問題