Visual Basic 6中的控件属性

时间:2009-12-04 14:49:10

标签: vb6 controls properties

有没有办法在循环中请求控件属性?

我需要这样的事情:

For each p in control.properties
    if p = "Value" then
        msgbox "I Have Value Property"
    elseif p = "Caption" then
        msgbox "I Have Caption Property"
    end if 
next

可以某种方式完成吗?

3 个答案:

答案 0 :(得分:5)

在Experts Exchange上找到此代码。添加对 TypeLib信息的引用。

Public Enum EPType
    ReadableProperties = 2
    WriteableProperties = 4
End Enum

Public Function EnumerateProperties(pObject As Object, pType As EPType) As Variant
    Dim rArray() As String
    Dim iVal As Long
    Dim TypeLib As TLI.InterfaceInfo
    Dim Prop As TLI.MemberInfo
    On Error Resume Next
    ReDim rArray(0) As String
    Set TypeLib = TLI.InterfaceInfoFromObject(pObject)
    For Each Prop In TypeLib.Members
        If Prop.InvokeKind = pType Then
            iVal = UBound(rArray)
            rArray(iVal) = UCase$(Prop.Name)
            ReDim Preserve rArray(iVal + 1) As String
        End If
    Next
    ReDim Preserve rArray(UBound(rArray) - 1) As String
    EnumerateProperties = rArray
End Function

您可以要求提供可读或可写属性的列表。

奖金,询问是否存在特定财产。

Public Function DoesPropertyExist(pObject As Object, ByVal _
    PropertyName As String, pType As EPType) As Boolean
    Dim Item As Variant
    PropertyName = UCase$(PropertyName)
    For Each Item In EnumerateProperties(pObject, pType)
        If Item = PropertyName Then
            DoesPropertyExist = True
            Exit For
        End If
    Next
End Function

答案 1 :(得分:2)

Beaner对你提出的问题给出了很好的direct answer

我猜你可能想做什么。也许你试图从控件中获取“文本”,但是你不知道运行时控件的类型。你可以考虑这样的东西,它依次尝试一些硬编码的属性名称,直到有效。

Function sGetSomeText(ctl As Object) As String 
  On Error Resume Next 
  sGetSomeText = ctl.Text
  If Err = 0 Then Exit Function 
  sGetSomeText = ctl.Caption
  If Err = 0 Then Exit Function 
  sGetSomeText = ctl.Value
  If Err = 0 Then Exit Function
  sGetSomeText = "" 'Nothing worked '
End Function 

另一种方法是在运行时检查控件的类型。你可以使用

然后你可以切换到具有Text属性的特定控件类型的代码等。

答案 2 :(得分:0)

我不确定你希望完成什么,但我很确定VB6不支持你所说的。你可以尝试这样的事情:

If control.Value Is Not Nothing Then
   msgbox "I Have Value Property"
Else If control.Caption Is Not Nothing Then
   msgbox "I Have Caption Property"

看看是否能完成你想要做的事情。