/
stdAcc.cls
1487 lines (1352 loc) · 59.8 KB
/
stdAcc.cls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "stdAcc"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'Spec:
'A class used to automate objects which implement IAccessible
'
'
'CONSTRUCTORS
' [X] CreateFromPoint
' [X] CreateFromHwnd
' [X] CreateFromApplication
' [X] CreateFromDesktop
' [X] CreateFromIAccessible
' [X] CreateFromMouse
'PUBLIC INSTANCE METHODS:
' [X] CreateFromPath
' [X] GetDescendents
' [X] FindFirst(stdICallable)
' [X] FindAll(stdICallable)
' [X] DoDefaultAction()
' [X] getPath
' [X] PrintChildTexts()
' [X] PrintDescTexts(sFile?)
' [X] SendMessage TODO: Consider removing when we have stdWindow?
' [ ] Highlight(seconds?) TODO: Requires implementation
' [ ] SendKeys() method TODO: Consider whether this would be useful or not
' [ ] SendKeysRaw() method TODO: Consider whether this would be useful or not
'PROPERTIES:
' [X] R Parent
' [X] R Children
' [X] R hwnd
' [X] R location
' [X] R HitTest TODO: Reconsider if this is useful
' [ ] R Selection TODO: Returns Collection<stdAcc>. Need to figure out how to do VT_I4 proxy children, without access to parent - does this matter?
' [X] R/W Value
' [X] R Name
' [X] R DefaultAction
' [X] R Role
' [X] R State
' [X] R Description
' [X] R KeyboardShortcut
' [X] R/W Focus
' [X] R Help
' [X] R HelpTopic
' [X] R Text
'PRIVATE INSTANCE METHODS
' getChildrenAsIAcc TODO: Consider moving this to `Children`
'GENERIC
'TODO: VB6 complient, 32-Bit complient, 64-Bit complient
'TODO: Error in hwnd - AccessibleObjectFromWindow returns an E_FAIL code. Potentially related to https://stackoverflow.com/a/8617584/6302131
' Need to test if coinitialise has any other affects on excel. Might also be related to Excel trying to access it's own object
' model? Not sure...
'For CreateFromMouse()
#If VBA7 Then
Private Declare PtrSafe Function GetCursorPos Lib "user32.dll" (lpPoint As tPOINT) As Long
'FIX: stdAcc::CreateFromPoint() crashes on 64-bit.
'The reason is that in reality the first arg of `AccessibleObjectFromPoint` is a ByVal `tPOINT` structure. Unfortunately in VBA you can't pass
'structs by value. a ByRef struct won't do however, so instead we have to fake the data by picking args with the same size. In 32-bit you used to be able
'to use 2 longs (the 2 parts of the struct), however 64-bit doesn't appear to like this notation. Instead we have to use a LongLong type to get the job done.
#If Win64 Then
Private Declare PtrSafe Function AccessibleObjectFromPoint Lib "oleacc" (ByVal arg1 As LongLong, ppacc As IAccessible, pVarChild As Variant) As Long
#Else
Private Declare PtrSafe Function AccessibleObjectFromPoint Lib "oleacc" (ByVal lX As Long, ByVal lY As Long, ppacc As IAccessible, pVarChild As Variant) As Long
#End If
#Else
Private Declare Function GetCursorPos Lib "user32.dll" (lpPoint As tPOINT) As Long
Private Declare Function AccessibleObjectFromPoint Lib "Oleacc" (ByVal lX As Long, ByVal lY As Long, ppacc As IAccessible, pvarChild As Variant) As Long
#End If
'
#If VBA7 Then
Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc" (ByVal hwnd As LongPtr, ByVal dwId As Long, riid As tGUID, ppvObject As Object) As Long
Private Declare PtrSafe Function AccessibleObjectFromEvent Lib "oleacc.dll" (hwnd As LongPtr, dwObjectId As Integer, dwChildID As Integer, ppacc As IAccessible, pVarChild As Object) As Long
Private Declare PtrSafe Function AccessibleChildren Lib "oleacc" (ByVal paccContainer As IAccessible, ByVal iChildStart As Long, ByVal cChildren As Long, rgvarChildren As Variant, pcObtained As Long) As Long
Private Declare PtrSafe Function WindowFromAccessibleObject Lib "oleacc" (ByVal pacc As IAccessible, ByRef pHwnd As LongPtr) As Long
Private Declare PtrSafe Function APISendMessage Lib "user32" Alias "SendMessage" (ByVal hwnd As LongPtr, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Declare PtrSafe Function CoTaskMemFree Lib "ole32" (ByVal pv As LongPtr) As Long
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal Destination As LongPtr, ByVal Source As LongPtr, ByVal Length As LongPtr)
Private Declare PtrSafe Function DispCallFunc Lib "oleAut32.dll" (ByVal pvInstance As LongPtr, ByVal offsetinVft As LongPtr, ByVal CallConv As Long, ByVal retTYP As Integer, ByVal paCNT As Long, ByVal paTypes As LongPtr, ByVal paValues As LongPtr, ByRef retVAR As Variant) As Long
Private Declare PtrSafe Function IIDFromString Lib "ole32.dll" (ByVal pstCLS As LongPtr, ByRef iid As GUID) As Long
#Else
Private Declare Function AccessibleObjectFromWindow Lib "oleacc" (ByVal hwnd As Long, ByVal dwId As Long, riid As tGUID, ppvObject As Object) As Long
Private Declare Function AccessibleObjectFromEvent Lib "oleacc.dll" (hwnd As Long, dwObjectId As Integer, dwChildID As Integer, ppacc As IAccessible, pVarChild As Object) As Long
Private Declare Function AccessibleChildren Lib "oleacc" (ByVal paccContainer As IAccessible, ByVal iChildStart As Long, ByVal cChildren As Long, rgvarChildren As Variant, pcObtained As Long) As Long
Private Declare Function WindowFromAccessibleObject Lib "oleacc" (ByVal pacc As IAccessible, ByRef pHwnd As Long) As Long
Private Declare Function APISendMessage Lib "user32" Alias "SendMessage" (ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Declare Function CoTaskMemFree Lib "ole32" (ByVal pv As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal Destination As Long, ByVal Source As Long, ByVal Length As LongPtr)
Private Declare Function DispCallFunc Lib "oleAut32.dll" (ByVal pvInstance As Long, ByVal offsetinVft As Long, ByVal CallConv As Long, ByVal retTYP As Integer, ByVal paCNT As Long, ByVal paTypes As Long, ByVal paValues As Long, ByRef retVAR As Variant) As Long
Private Declare Function IIDFromString Lib "ole32.dll" (ByVal pstCLS As Long, ByRef iid As GUID) As Long
#End If
'GUID struct for QueryInterface
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(0 To 7) As Byte
End Type
'Used while walking the Accessibility tree. Can be used to toggle between a Breadth first search and a depth first search.
Public Enum EAccFindType
BreadthFirst = 0
DepthFirst = 1
End Enum
'Used while walking the Accessibility tree. Can be used to discard entire trees of elements, to increase speed of walk algorithms.
Public Enum EAccFindResult
MatchFound = 1 'Matched
MatchFoundSearchDescendents=4 'Same as `ESearchResult.MatchFound`
NoMatchFound = 0 'Not found, continue searching descendents
NoMatchCancelSearch= 2 'Not found, cancel search
NoMatchSkipDescendents= 3 'Not found, don't search descendents
End Enum
Public Enum EAccRoles
ROLE_TITLEBAR = &H1&
ROLE_MENUBAR = &H2&
ROLE_SCROLLBAR = &H3&
ROLE_GRIP = &H4&
ROLE_SOUND = &H5&
ROLE_CURSOR = &H6&
ROLE_CARET = &H7&
ROLE_ALERT = &H8&
ROLE_WINDOW = &H9&
ROLE_CLIENT = &HA&
ROLE_MENUPOPUP = &HB&
ROLE_MENUITEM = &HC&
ROLE_TOOLTIP = &HD&
ROLE_APPLICATION = &HE&
ROLE_DOCUMENT = &HF&
ROLE_PANE = &H10&
ROLE_CHART = &H11&
ROLE_DIALOG = &H12&
ROLE_BORDER = &H13&
ROLE_GROUPING = &H14&
ROLE_SEPARATOR = &H15&
ROLE_TOOLBAR = &H16&
ROLE_STATUSBAR = &H17&
ROLE_TABLE = &H18&
ROLE_COLUMNHEADER = &H19&
ROLE_ROWHEADER = &H1A&
ROLE_COLUMN = &H1B&
ROLE_ROW = &H1C&
ROLE_CELL = &H1D&
ROLE_LINK = &H1E&
ROLE_HELPBALLOON = &H1F&
ROLE_CHARACTER = &H20&
ROLE_LIST = &H21&
ROLE_LISTITEM = &H22&
ROLE_OUTLINE = &H23&
ROLE_OUTLINEITEM = &H24&
ROLE_PAGETAB = &H25&
ROLE_PROPERTYPAGE = &H26&
ROLE_INDICATOR = &H27&
ROLE_GRAPHIC = &H28&
ROLE_STATICTEXT = &H29&
ROLE_TEXT = &H2A&
ROLE_PUSHBUTTON = &H2B&
ROLE_CHECKBUTTON = &H2C&
ROLE_RADIOBUTTON = &H2D&
ROLE_COMBOBOX = &H2E&
ROLE_DROPLIST = &H2F&
ROLE_PROGRESSBAR = &H30&
ROLE_DIAL = &H31&
ROLE_HOTKEYFIELD = &H32&
ROLE_SLIDER = &H33&
ROLE_SPINBUTTON = &H34&
ROLE_DIAGRAM = &H35&
ROLE_ANIMATION = &H36&
ROLE_EQUATION = &H37&
ROLE_BUTTONDROPDOWN = &H38&
ROLE_BUTTONMENU = &H39&
ROLE_BUTTONDROPDOWNGRID = &H3A&
ROLE_WHITESPACE = &H3B&
ROLE_PAGETABLIST = &H3C&
End Enum
Public Enum EAccStates
STATE_NORMAL = &H0
STATE_UNAVAILABLE = &H1
STATE_SELECTED = &H2
STATE_FOCUSED = &H4
STATE_PRESSED = &H8
STATE_CHECKED = &H10
STATE_MIXED = &H20
STATE_INDETERMINATE = &H99
STATE_READONLY = &H40
STATE_HOTTRACKED = &H80
STATE_DEFAULT = &H100
STATE_EXPANDED = &H200
STATE_COLLAPSED = &H400
STATE_BUSY = &H800
STATE_FLOATING = &H1000
STATE_MARQUEED = &H2000
STATE_ANIMATED = &H4000
STATE_INVISIBLE = &H8000
STATE_OFFSCREEN = &H10000
STATE_SIZEABLE = &H20000
STATE_MOVEABLE = &H40000
STATE_SELFVOICING = &H80000
STATE_FOCUSABLE = &H100000
STATE_SELECTABLE = &H200000
STATE_LINKED = &H400000
STATE_TRAVERSED = &H800000
STATE_MULTISELECTABLE = &H1000000
STATE_EXTSELECTABLE = &H2000000
STATE_ALERT_LOW = &H4000000
STATE_ALERT_MEDIUM = &H8000000
STATE_ALERT_HIGH = &H10000000
STATE_PROTECTED = &H20000000
STATE_VALID = &H7FFFFFFF
End Enum
'Not sure if this is the correct order, not sure if it's even needed given IAccessible apparently implements IDispatch...
Private Enum IAccessible_Methods
accDoDefaultAction
accHitTest
accLocation
accNavigate
accSelect
get_accChild
get_accChildCount
get_accDefaultAction
get_accDescription
get_accFocus
get_accHelp
get_accHelpTopic
get_accKeyboardShortcut
get_accName
get_accParent
get_accRole
get_accSelection
get_accState
get_accValue
put_accName
put_accValue
End Enum
'@TODO: Convert to TThis
Private isProxy As Boolean
Private proxyParent As IAccessible 'IAcc
Private proxyIndex As Long
Private Lookups As Object
'GUID type for ObjectFromWindow
Private Type tGUID
lData1 As Long
nData2 As Integer
nData3 As Integer
abytData4(0 To 7) As Byte
End Type
Private Type tPOINT
x As Long
y As Long
End Type
Private Type tFindNode
initialised as boolean
depth as long
element as object
End Type
Const CHILDID_SELF = 0&
'The object which implements `IAccessible`, with which this class wraps. Please don't modify this object, unless you know what you are doing.
'@protected
Public protAccessible As Object
'****************
'* Constructors *
'****************
'Creates an `stdAcc` object from an `X` and `Y` point location on the screen.
'@constructor
'@param x - X Coordinate
'@param y - Y Coordinate
'@returns stdAcc - Object at the specified point
Public Function CreateFromPoint(ByVal x As Long, ByVal y As Long) As stdAcc
Set CreateFromPoint = New stdAcc
set CreateFromPoint.protAccessible = AccessibilityObjectFromPointEx(x,y)
End Function
'Creates an `stdAcc` object from a window handle.
'@constructor
'@param hwnd - Window handle to wrap
'@returns stdAcc - stdAcc object for the window
Public Function CreateFromHwnd(ByVal hwnd As LongPtr) As stdAcc
Dim acc as stdAcc: set acc = new stdAcc
Dim obj As IAccessible
Set obj = IAccessibleFromHwnd(hwnd)
set acc.protAccessible = obj
Set CreateFromHwnd = acc
End Function
'Creates an `stdAcc` object from the current running application (e.g. Excel / Word / Powerpoint).
'@constructor
'@param oApp - Application to create from. Defaults to `Application` if unspecified.
'@returns - IAccessible wrapper around application window.
Public Function CreateFromApplication(Optional ByVal oApp as Object = Nothing) As stdAcc
if oApp is nothing then set oApp = Application
select case oApp.Name
case "Microsoft Excel"
Set CreateFromApplication = CreateFromHwnd(oApp.hwnd)
case "Microsoft Word"
Set CreateFromApplication = CreateFromHwnd(oApp.ActiveWindow.Hwnd)
case "Microsoft Access"
set CreateFromApplication = CreateFromHwnd(oApp.hWndAccessApp)
case "Microsoft PowerPoint"
set CreateFromApplication = CreateFromIAccessible(oApp.CommandBars("Status Bar")).AncestralRoot
Case "Outlook"
Set CreateFromApplication = CreateFromIAccessible(oApp.ActiveWindow.CommandBars("Status Bar")).AncestralRoot
Case "Microsoft Publisher"
Set CreateFromApplication = CreateFromIAccessible(oApp.CommandBars("Status Bar")).AncestralRoot
case else
Err.Raise 1, "stdAcc::CreateFromApplication()", "No implementation for getting application window of " & Application.name
end select
End Function
'Creates an `stdAcc` object from the desktop.
'@constructor
'@returns - IAccessible wrapper around desktop window.
Public Function CreateFromDesktop() As stdAcc
'Get this application's accessibility object
Dim accThis As IAccessible
Set accThis = IAccessibleFromHwnd(Application.hwnd)
'Set desktop
Dim accDesktop As IAccessible
Set accDesktop = accThis.accParent
Dim acc as stdAcc: set acc = new stdAcc
set acc.protAccessible = accDesktop
Set CreateFromDesktop = acc
End Function
'Creates an `stdAcc` object from an object which implements `IAccessible`.
'@constructor
'@param obj - Object implementing `IAccessible` interface.
'@returns - IAccessible wrapper around an IAccessible object.
Public Function CreateFromIAccessible(ByVal obj As IAccessible) As stdAcc
Set CreateFromIAccessible = New stdAcc
set CreateFromIAccessible.protAccessible = obj
End Function
'Creates an `stdAcc` object for the element the mouse currently hovers over.
'@constructor
'@returns - IAccessible wrapper around element under mouse.
Public Function CreateFromMouse() As stdAcc
Dim pT As tPOINT
Dim success As Long
success = GetCursorPos(pT)
Set CreateFromMouse = CreateFromPoint(pt.x,pt.y)
End Function
'Creates an `stdAcc` object for the element at a given path from the current element.
'@constructor
'@param sPath - Path to element, e.g. "P.1.2.3" or "1.2.3". If starting with "P." or ".", these are ignored as they are taken as the current element.
'@returns - IAccessible wrapper from a supplied path.
'@example `Debug.Print stdAcc.CreateFromApplication().CreateFromPath("3.1").name`
Public Function CreateFromPath(ByVal sPath As String) As stdAcc
'If starting with "." remove it
If left(sPath, 1) = "P" Then sPath = Mid(sPath, 2)
If left(sPath, 1) = "." Then sPath = Mid(sPath, 2)
'Get descendants list
Dim descendants As Variant
descendants = Split(sPath, ".")
'Initiate acc (used for tracing through descendants)
Dim acc As stdAcc
Set acc = Me
'Loop over descendants
On Error GoTo ExitFunction 'theoretically this should never error, but still sometimes does...
Dim i As Integer
For i = 0 To UBound(descendants)
If CLng(descendants(i)) > acc.children.Count Then Exit Function
Set acc = acc.children(CLng(descendants(i)))
Next i
On Error GoTo 0
'Return descendant
Set CreateFromPath = acc
ExitFunction:
End Function
'Initialises an stdAcc object as a `Proxy` object, who's methods are implemented on the parent instead of on the element itself
'@constructor
'@protected
'@param oParent - Parent object to proxy
'@param index - Index of element in parent
Public Sub protInitWithProxy(ByRef oParent as stdAcc, ByVal index as long)
isProxy = true
set proxyParent = oParent.protAccessible
proxyIndex = index
End Sub
'Get all descendents of the stdAcc control
'@returns Collection<stdAcc> - Collection of descendents
Public Function GetDescendents() As Collection
'Create collection which will be returned
Dim c As Collection
Set c = New Collection
'Loop over all children...
Dim accChild As stdAcc, accDesc As stdAcc
For Each accChild In children
'Add children to collection
c.Add accChild
'Loop over descendents and add these to collection also (recurse)
For Each accDesc In accChild.GetDescendents
c.Add accDesc
Next
Next
'Return descendents
Set GetDescendents = c
End Function
'Search the IAccessible tree for elements which match a certain criteria. Return the first element found.
'@param query as stdICallable<(stdAcc,depth)=>EAccFindResult> - Callback returning `EAccFindResult` options:
'
'* `EAccFindResult.NoMatchFound`/`0`/`False` - Not found, countinue walking
'* `EAccFindResult.MatchFound`/`1`/`-1`/`True` - Found, return this element
'* `EAccFindResult.NoMatchCancelSearch`/`2` - Not found, cancel search
'* `EAccFindResult.NoMatchSkipDescendents`/`3` - Not found, don't search descendents
'* `EAccFindResult.MatchFoundSearchDescendents`/`4` - Same as `EAccFindResult.MatchFound` in this case.
'@param searchType - The type of search to perform, either Breadth First Search (BFS) or Depth First Search (DFS).
' To understand the difference between BFS and DFS take this tree:
'```
' A
' / \
' B C
' / / \
' D E F
'```
'
'* A BFS will walk this tree in the following order: A, B, C, D, E, F
'* A DFS will walk this tree in a different order: A, C, F, E, B, D
'@returns {stdAcc} - Element found.
'@examples ```
''Find where name is "hello" and class is "world":
'el.FindFirst(stdLambda.Create("$1.name=""hello"" and $1.class=""world"""))
''Find first element named "hello" at depth > 4:
'el.FindFirst(stdLambda.Create("$1.name = ""hello"" AND $2 > 4"))
'```
Public Function FindFirst(ByVal query As stdICallable, optional byval searchType as EAccFindType=EAccFindType.DepthFirst) As stdAcc
Dim stack() As tFindNode
ReDim stack(0 To 0)
stack(0).initialised = true
stack(0).depth = 0
Set stack(0).element = Me
Dim length As Long: length = 1
Dim index As Long: index = -1
'Bind globals to query
Call BindGlobals(query)
'Loop over the stack/array
While length > 0 And index < length
Dim part As tFindNode
select case searchType
case EAccFindType.DepthFirst
'Depth first search, so pop the item out of the stack
part = stackPopV(stack,length)
case EAccFindType.BreadthFirst
'Breadth first search, get item directly out of array, no need to change array size
index = index + 1
part = stack(index)
case else
Err.Raise 1, "stdAcc#FindFirst", "Invalid search type given. Please use EAccFindType"
end select
With part
If not .initialised Then Exit Function
'Run query and test options
Select Case query.Run(.element, .depth)
Case EAccFindResult.NoMatchFound
'Nothing found, search descendents
Dim child As stdAcc
For Each child In part.element.children
Call stackPushV(stack, length, CreateFindNode(.depth + 1, child))
Next
Case EAccFindResult.MatchFound, True, EAccFindResult.MatchFoundSearchDescendents
'Found, return element
Set FindFirst = .element
Exit Function
Case EAccFindResult.NoMatchCancelSearch
'Nothing found, cancel function
Set FindFirst = Nothing
Exit Function
case EAccFindResult.NoMatchSkipDescendents
' Nothing found, don't search descendents
End Select
End With
'Just make sure no freezing occurs
DoEvents
Wend
'Else set to nothing
Set FindFirst = Nothing
End Function
'Search the IAccessible tree for elements which match a certain criteria. Return all elements found.
'@param query as stdICallable<(stdAcc,depth)=>EAccFindResult> - Callback returning `EAccFindResult` options:
'
'* `EAccFindResult.NoMatchFound`/`0`/`False` - Not found, countinue walking.
'* `EAccFindResult.MatchFound`/`1`/`-1`/`True` - Found, return this element, won't search descendents of elements found.
'* `EAccFindResult.NoMatchCancelSearch`/`2` - Not found, cancel search.
'* `EAccFindResult.NoMatchSkipDescendents`/`3` - Not found, don't search descendents.
'* `EAccFindResult.MatchFoundSearchDescendents`/`4` - Found, return this element, but continue searching descendents.
'@param searchType - The type of search, either Breadth First Search (BFS) or Depth First Search (DFS).
' To understand the difference between BFS and DFS take this tree:
'```
' A
' / \
' B C
' / / \
' D E F
'```
'
'* A BFS will walk this tree in the following order: A, B, C, D, E, F.
'* A DFS will walk this tree in a different order: A, C, F, E, B, D.
'@returns Collection<stdAcc> - Collection of elements found.
'@examples ```
''Find where name is "hello" and class is "world":
'el.FindAll(stdLambda.Create("$1.name=""hello"" and $1.class=""world"""))
''Find all elements with depth <= 4:
'el.FindAll(stdLambda.Create("if $2 < 4 then 4 else if $2 = 4 then 1 else 3"))
'```
Public Function FindAll(ByVal query As stdICallable, optional byval searchType as EAccFindType=EAccFindType.DepthFirst) As Collection
Dim stack() As tFindNode
ReDim stack(0 To 0)
stack(0).initialised = true
stack(0).depth = 0
Set stack(0).element = Me
Dim length As Long: length = 1
Dim index As Long: index = -1
'Bind globals to query
Call BindGlobals(query)
'Initialise collection
set FindAll = new Collection
'Loop over the stack/array
While length > 0 And index < length
Dim part as tFindNode
select case searchType
case EAccFindType.DepthFirst
'Depth first search, so pop the item out of the stack
part = stackPopV(stack,length)
case EAccFindType.BreadthFirst
'Breadth first search, get item directly out of array, no need to change array size
index = index + 1
part = stack(index)
case else
Err.Raise 1, "stdAcc#FindAll", "Invalid search type given. Please use EAccFindType"
end select
With part
'When hitting the edge of the stack quit
if not .initialised then Exit Function
'Run query and test options
Dim child as stdAcc
select case query.Run(.element,.depth)
Case EAccFindResult.NoMatchFound
'Nothing found, search descendents
for each child in .element.children
Call stackPushV(stack,length,CreateFindNode(.depth+1,child))
next
Case EAccFindResult.MatchFound, True
'Found, add element
Call FindAll.add(.element)
Case EAccFindResult.NoMatchCancelSearch
'Nothing found, cancel function
Exit Function
Case EAccFindResult.NoMatchSkipDescendents
'Nothing found, don't search descendents
Case EAccFindResult.MatchFoundSearchDescendents
Call FindAll.add(.element)
for each child in .element.children
Call stackPushV(stack,length,CreateFindNode(.depth+1,child))
next
end select
End with
'Just make sure no freezing occurs
DoEvents
Wend
End Function
'Return the parent of the IAccessible object
'@returns stdAcc - Parent of this element
Public Property Get Parent() As stdAcc
If isProxy Then
Set Parent = stdAcc.CreateFromIAccessible(proxyParent)
else
On Error GoTo handle_error
Set Parent = stdAcc.CreateFromIAccessible(protAccessible.accParent)
On Error GoTo 0
End if
Exit Property
handle_error:
Set Parent = Nothing
End Property
'Obtain the ancestral root of the IAccessible object (A child of the desktop)
'@returns - Ancestral root of this element (child window of the desktop)
Public Property Get AncestralRoot() As stdAcc
Dim desktop as stdAcc: set desktop = stdAcc.CreateFromDesktop()
'Walk up the tree until we hit the element just before desktop
Dim acc As stdAcc: Set acc = Me
While Not acc.Parent.hwnd <> desktop.hwnd
Set acc = acc.Parent
Wend
Set AncestralRoot = acc
End Property
'Return the children of the IAccessible object
'@returns Collection<stdAcc> - Children of this element
Public Property Get children() As Collection
On Error GoTo ErrorHandler
Set children = getChildrenAsIAcc()
On Error GoTo 0
Exit Property
ErrorHandler:
Set children = New Collection
End Property
'Return the hwnd of the IAccessible object
'@returns LongPtr - hwnd of this element
#if VBA7 then
Public Property Get hwnd() As LongPtr
#Else
Public Property Get hwnd() As Long
#End If
On Error GoTo handle_error
Dim lHwnd As LongPtr
Dim res As Long
res = WindowFromAccessibleObject(protAccessible, lHwnd)
If res = 0 Then
hwnd = lHwnd
Else
Call Err.Raise(1, "", "Error " & Hex(res) & " - " & COMErrorDescription(res) & " in stdAcc#hwnd")
End If
On Error GoTo 0
Exit Property
handle_error:
hwnd = 0
End Property
'Get a unique identifier for an element.
'@returns string - Hex string identifier for element.
'@example `stdAcc.CreateFromMouse().Identity`
Public Property Get Identity() As String
On Error GoTo Fallback
Dim accIdent As IUnknown: Set accIdent = unkQueryInterface(protAccessible, "{7852B78D-1CFD-41C1-A615-9C0C85960B5F}")
If Not accIdent Is Nothing Then Identity = accGetIdentity(accIdent)
Exit Property
Fallback:
'TODO: Fallback identity
Identity = "Unknown"
End Property
'Return the location of the element as a collection
'@returns Collection<Long|stdAcc> - The location of the element. Collection has 5 named keys: "Width", "Height", "Left", "Top" and "Parent". "Parent" refers to the element itself.
Public Property Get Location() As Collection
On Error GoTo ErrorHandler
'Get location from protAccessible
Dim pcxWidth As Long
Dim pcyHeight As Long
Dim pxLeft As Long
Dim pyTop As Long
Call protAccessible.accLocation(pxLeft, pyTop, pcxWidth, pcyHeight, CHILDID_SELF)
'Create location collection
Set Location = New Collection
Location.Add pcxWidth, "Width"
Location.Add pcyHeight, "Height"
Location.Add pxLeft, "Left"
Location.Add pyTop, "Top"
Location.Add Me, "Parent"
On Error GoTo 0
Exit Property
ErrorHandler:
Set Location = Nothing
End Property
'Return the element under the specified location
'TODO: Is this needed?
'@param x - x coord
'@param y - y coord
'@returns stdAcc - element under point
Public Property Get HitTest(ByVal x As Long, ByVal y As Long) As stdAcc
Set HitTest = New stdAcc
Dim NewAcc As Object
Call protAccessible.accHitTest(x, y, NewAcc)
set HitTest.protAccessible = NewAcc
End Property
'Gets/Sets the value of the element
'@returns String - the current value of the element
Public Property Get value() As String
On Error Resume Next 'FIX: Sometimes this is unsupported, so leave this error.
if isProxy then
value = proxyParent.accValue(proxyIndex)
else
value = protAccessible.accValue(CHILDID_SELF)
end if
End Property
Public Property Let value(val As String)
if isProxy then
proxyParent.accValue(proxyIndex) = val
else
protAccessible.accValue(CHILDID_SELF) = val
end if
End Property
'Returns the name of the element
'@returns String - the name of the element
Public Property Get name() As String
On Error Resume Next 'FIX: Sometimes this is unsupported, so leave this error.
If isProxy Then
name = proxyParent.accName(proxyIndex)
Else
name = protAccessible.accName(CHILDID_SELF)
End If
End Property
'Returns the description of the default action of the element
'@returns String - the description of the default action of the element
Public Property Get DefaultAction() As String
On Error Resume Next 'FIX: Sometimes this is unsupported, so leave this error.
If isProxy Then
DefaultAction = proxyParent.accDefaultAction(proxyIndex)
else
DefaultAction = protAccessible.accDefaultAction(CHILDID_SELF)
end if
End Property
'Returns the role of the element
'@returns String - the role of the element
Public Property Get Role() As String
On Error Resume Next 'FIXME: On extremely rare occasions the OLE object will disconnect / not expect automation. `On Error Resume Next` silences the error but this isn't a real fix.
if isProxy then
Role = Lookups("EAccRoles")("N2S")(proxyParent.accRole(proxyIndex))
else
Role = Lookups("EAccRoles")("N2S")(protAccessible.accRole(CHILDID_SELF))
end if
End Property
'Returns the state of the element
'@returns String - the state of the element
Public Property Get States() As String
Dim iStateData As Long: iStateData = StateData
Dim oLookup As Object: Set oLookup = Lookups("EAccStates")("S2N")
Dim sStates As String, vKey as variant
For Each vKey In oLookup.keys()
If (oLookup(vKey) And iStateData) = oLookup(vKey) Then
sStates = sStates & vKey & ";"
End If
Next
States = sStates
End Property
'Returns the state(s) of the element
'@returns Long - the state(s) of the element
Public Property Get StateData() As Long
On Error Resume Next 'FIXME: On extremely rare occasions the OLE object will disconnect / not expect automation. `On Error Resume Next` silences the error but this isn't a real fix.
if isProxy then
StateData = proxyParent.accState(proxyIndex)
else
StateData = protAccessible.accState(CHILDID_SELF)
end if
End Property
'Returns the description of the element
'@returns String - the description of the element
Public Property Get Description() As String
On Error Resume Next 'FIX: Sometimes this is unsupported, so leave this error.
if isProxy then
Description = proxyParent.accDescription(proxyIndex)
else
Description = protAccessible.accDescription(CHILDID_SELF)
end if
End Property
'Returns the keyboard shortcut used to trigger the default action of the element
'@returns String - The keyboard shortcut used to trigger the default action of the element
Public Property Get KeyboardShortcut() As String
On Error Resume Next 'FIX: Sometimes this is unsupported, so leave this error handling.
if isProxy then
KeyboardShortcut = proxyParent.accKeyboardShortcut(proxyIndex)
else
KeyboardShortcut = protAccessible.accKeyboardShortcut(CHILDID_SELF)
end if
End Property
'Get the Focus of the UI element
'@returns Boolean - Whether the element has focus
Public Property Get Focus() As Boolean
'On Error Resume Next
if isProxy then
Focus = proxyParent.accFocus(proxyIndex)
else
Focus = protAccessible.accFocus(CHILDID_SELF)
end if
End Property
'Set the Focus of the UI element
'@param Boolean - `True` if the element should be focussed, otherwise `false`
Public Property Let Focus(ByVal val As Boolean)
'On Error Resume Next
if isProxy then
proxyParent.accFocus(proxyIndex) = val
else
protAccessible.accFocus(CHILDID_SELF) = val
end if
End Property
'Returns the help
'@returns String - the help for the element
Public Property Get Help() As String
On Error Resume Next 'FIX#97: Sometimes this is unsupported, so leave this error handling.
if isProxy then
Help = proxyParent.accHelp(proxyIndex)
else
Help = protAccessible.accHelp(CHILDID_SELF)
end if
End Property
'Returns the help topic
'@param sFile - File to get help topic for
'@returns - the help topic for the element
Public Property Get HelpTopic(Optional ByVal sFile as string = "") As String
On Error Resume Next 'FIX: Sometimes this is unsupported, so leave this error.
if isProxy then
HelpTopic = proxyParent.accHelpTopic(sFile, proxyIndex)
else
HelpTopic = protAccessible.accHelpTopic(sFile, CHILDID_SELF)
end if
End Property
'Returns a string containing numerous properties from stdAcc concatenated together.
'@returns String - Concatenation of Name, Value, DefaultAction, Description, Role, Help, HelpTopic and KeyboardShortcut.
Public Property Get Text() As String
If Len(name & value & DefaultAction & Description & Help & HelpTopic & KeyboardShortcut) > 0 Then
Text = "Name: """ & name & """; " & _
"Value: """ & value & """; " & _
"DefaultAction: """ & DefaultAction & """; " & _
"Description: """ & Description & """; " & _
"Role: """ & Role & """; " & _
"Help: """ & Help & """; " & _
"HelpTopic: """ & HelpTopic & """; " & _
"KeyboardShortcut: """ & KeyboardShortcut & """;"
Else
Text = ""
End If
End Property
'Performs the default action of the `IAccessible` object
Public Sub DoDefaultAction()
If isProxy Then
Call proxyParent.accDoDefaultAction(proxyIndex)
Else
Call protAccessible.accDoDefaultAction(CHILDID_SELF)
End If
End Sub
'Sends a message to the window
'@deprecated Use `stdWindow#SendMessage()` instead.
'@param Msg - Message to send
'@param wParam - WParam to send
'@param lParam - LParam to send
'@returns Long - Return value
Public Function SendMessage(ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
If hwnd() > 0 Then
SendMessage = APISendMessage(hwnd(), Msg, wParam, lParam)
Else
Err.Raise 1, "No hwnd on this window"
End If
End Function
'Print the text of all child elements. Useful for debugging.
Public Sub PrintChildTexts()
Dim child As stdAcc
Dim iIndex As Long: iIndex = 0
For Each child In children
iIndex = iIndex + 1
Debug.Print iIndex & ". " & child.Text
Next
End Sub
'Prints all descendent texts. Useful for debugging. Also includes all paths of all descendents which can be very beneficial.
'@param sToFilePath - File path to dump text to.
'@param bPrintToDebug - Whether to print output to debug window or not.
'@param sPath - Prefix path (sometimes you might wnat to use Me.getPath(...))
'@param fileNum - Filenum to output too, typically this will be left unprovided
Public Sub PrintDescTexts(Optional ByVal sToFilePath as string = "", Optional ByVal bPrintToDebug as boolean = true, Optional ByVal sPath As String = "P", Optional ByVal fileNum as long = 0)
'Open file is file name passed and file num not given
Dim bFileOpened as boolean
if fileNum = 0 and len(sToFilePath) > 0 then
bFileOpened = true
fileNum = FreeFile()
open sToFilePath for Output as #fileNum
end if
'Loop over all children
Dim child As stdAcc
Dim iIndex As Long: iIndex = 0
For Each child In children
'Get child index for path
iIndex = iIndex + 1
'Create path string
Dim myPath As String: myPath = sPath & "." & iIndex
'If file has been opened, print data to file
If fileNum <> 0 Then Print #fileNum, myPath & ". " & child.Text
'Only print to debug if bPrintToDebug
if bPrintToDebug then Debug.Print myPath & ". " & child.Text
'Recurse to all children
Call child.PrintDescTexts(sToFilePath, bPrintToDebug, myPath, fileNum)
Next
'Only close file if file was opened within sub
if bFileOpened then
Close #fileNum
end if
End Sub
'Returns the path to an element
'@param toAccessible - Stop creating path at this element
'@returns String - String representing path to element from either Desktop or toAccessible.
Public Function getPath(Optional toAccessible As stdAcc = Nothing) As String
'Initialise trace
Dim acc As stdAcc
Set acc = Me
'Collection to store path
Dim col As Collection: Set col = New Collection
'Collect parents
if not acc.parent is nothing then
While Not acc.parent.name = "Desktop"
Dim child As stdAcc
Dim index As Long: index = 0
Dim savedIndex As Long: savedIndex = 0
For Each child In acc.parent.children
index = index + 1
If child.hwnd = acc.hwnd And child.Role = acc.Role Then
savedIndex = index
Exit For
End If
Next
'Add index to stack
If savedIndex > 0 Then
col.add savedIndex
Else
'In some scenarios this has occurred where acc tree has changed after initial pass. Not much we can do if this is the case.
getPath = "UNKNOWN"
Exit Function
End If
'Elevate parent
Set acc = acc.parent
Wend
'Create path
Dim path As String
Dim i As Integer
For i = col.Count To 1 Step -1
path = path & "." & col(i)
Next i
'Return path
getPath = "D.W" & path
else
getPath = "D"