我正在研究VB.NET项目,以使用COM Interop操纵VB6表单。我的VB6表单上的某些控件已编入索引,而有些则未编入索引,因此在没有索引的控件上调用ctl.Index失败。如果索引了控件,有没有办法解决?
在vb6中,您可以使用TypeName函数-控件数组将返回类型“ Object”,而不是实际的控件类型-像这样:
If TypeName(ctrl) = "Object" Then
isControlArray = true
End If
我设法解决了这个问题。但这并不是那么有效,因为每次都遍历表单上的所有控件。我似乎记得在我的脑海中,有一个VB6函数可以测试控件是否为数组,但我不记得它了。我对有兴趣的人的作用如下,但如果可能的话,我仍然有兴趣找到一种更清洁的解决方案?
Private Function FindIndex(ByRef objCtl As Object) As Integer
For Each ctl As Object In objCtl.Parent.Controls
If objCtl.Name = ctl.Name AndAlso Not objCtl.Equals(ctl) Then
'if the object is the same name but is not the same object we can assume it is a control array
Return objCtl.Index
End If
Next
'if we get here then no controls on the form have the same name so can't be a control array
Return 0
End Function
以下是等效的VB6,如果有人有兴趣:
Private Function FindIndex(ByRef F As Form, ByRef Ctl As Control) As Integer
Dim ctlTest As Control
For Each ctlTest In F.Controls
If (ctlTest.Name = Ctl.Name) And (Not (ctlTest Is Ctl)) Then
'if the object is the same name but is not the same object we can assume it is a control array
FindIndex = Ctl.Index
Exit Function
End If
Next
'if we get here then no controls on the form have the same name so can't be a control array
FindIndex = 0
End Function
我发现了一种类似于@Matt Wilko的解决方案,但它避免了循环浏览表单上的所有控件:
Public Function IsControlArray(objCtrl As Object) As Boolean
IsControlArray = Not objCtrl.Parent.Controls(objCtrl.Name) Is objCtrl
End Function
来源:http://www.vbforums.com/showthread.php?536960-RESOLVED-how-can-i-see-if-the-object-is-array-or-not
如果控制数组只有一个成员,则上面提出的解决方案将不起作用。测试控件是否作为控件数组成员的一种简单方法是测试控件的Index属性(控件数组)。这将返回唯一标识控件数组中的控件的数字。仅当控件是控件数组的一部分时可用。
Private Function IsControlArray(Ctl As Control) As Boolean
On Error GoTo NotArray
IsControlArray = IsNumeric(Ctl.Index)
Exit Function
NotArray:
IsControlArray = False
End Function