Skip to content

Instantly share code, notes, and snippets.

@voltwu
Created July 19, 2021 14:50
Show Gist options
  • Save voltwu/fe90b3e7dd001c11228597f0ac29ab19 to your computer and use it in GitHub Desktop.
Save voltwu/fe90b3e7dd001c11228597f0ac29ab19 to your computer and use it in GitHub Desktop.
An example of UI Automation on VBA
Dim oAutomation As New CUIAutomation
Sub Test()
Dim MyElement1 As UIAutomationClient.IUIAutomationElement
Set MyElement1 = WalkEnabledElements(oAutomation.GetRootElement, "WeChat")
Dim MyElement2 As UIAutomationClient.IUIAutomationElement
Set MyElement2 = MyElement1.FindFirst(TreeScope_Children, PropCondition(oAutomation, "Open", "Name")) 'open
Dim MyElement3 As UIAutomationClient.IUIAutomationElement
Set MyElement3 = MyElement2.FindFirst(TreeScope_Children, PropCondition(oAutomation, "1148", "AutoID")) 'pane
Dim MyElement4 As UIAutomationClient.IUIAutomationElement
Set MyElement4 = MyElement3.FindFirst(TreeScope_Children, PropCondition(oAutomation, "File name:", "Name")) 'comboBox
'perform input
Dim oPattern As UIAutomationClient.IUIAutomationLegacyIAccessiblePattern
Set oPattern = MyElement4.GetCurrentPattern(UIAutomationClient.UIA_LegacyIAccessiblePatternId)
oPattern.SetValue ("Hello")
Dim MyElement5 As UIAutomationClient.IUIAutomationElement
Set MyElement5 = MyElement2.FindFirst(TreeScope_Children, PropCondition(oAutomation, "1", "AutoID")) 'open
'perform click
Dim oInvokePattern As UIAutomationClient.IUIAutomationInvokePattern
Set oInvokePattern = MyElement5.GetCurrentPattern(UIAutomationClient.UIA_InvokePatternId)
oInvokePattern.Invoke
End Sub
Function PropCondition(UIAutomation As CUIAutomation, Requirement As String, IdType As String) As UIAutomationClient.IUIAutomationCondition
Select Case IdType
Case "Name":
Set PropCondition = UIAutomation.CreatePropertyCondition(UIAutomationClient.UIA_NamePropertyId, Requirement)
Case "AutoID":
Set PropCondition = UIAutomation.CreatePropertyCondition(UIAutomationClient.UIA_AutomationIdPropertyId, Requirement)
Case "ClsName":
Set PropCondition = UIAutomation.CreatePropertyCondition(UIAutomationClient.UIA_ClassNamePropertyId, Requirement)
Case "LoczCon":
Set PropCondition = UIAutomation.CreatePropertyCondition(UIAutomationClient.UIA_LocalizedControlTypePropertyId, Requirement)
End Select
End Function
Function WalkEnabledElements(element As UIAutomationClient.IUIAutomationElement, strWIndowName As String) As UIAutomationClient.IUIAutomationElement
Dim walker As UIAutomationClient.IUIAutomationTreeWalker
Set walker = oAutomation.ControlViewWalker
Set element = walker.GetFirstChildElement(element)
Do While Not element Is Nothing
If InStr(1, element.CurrentName, strWIndowName) > 0 Then
Set WalkEnabledElements = element
Exit Function
End If
Set element = walker.GetNextSiblingElement(element)
Loop
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment