-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathclass_UIA_Interface.ahk
3769 lines (3519 loc) · 201 KB
/
class_UIA_Interface.ahk
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
/*
Introduction & credits
This library implements Microsoft's UI Automation framework. More information is here: https://docs.microsoft.com/en-us/windows/win32/winauto/entry-uiauto-win32
Credit for this file mostly goes to jethrow: https://github.com/jethrow/UIA_Interface/blob/master/UIA_Interface.ahk
I have added a lot of modifications to it, including custom methods for elements (eg element.Click()), UIA_Enum class etc
*/
/*
Usage
UIA needs to be initialized with UIA_Interface() function, which returns a UIA_Interface object:
UIA := UIA_Interface()
After calling this function, all UIA_Interface class properties and methods can be accessed through it.
In addition some extra variables are initialized:
CurrentVersion contains the version number of IUIAutomation interface
TrueCondition contains a UIA_TrueCondition
TreeWalkerTrue contains an UIA_TreeWalker that was created with UIA_TrueCondition
Note that a new UIA_Interface object can't be created with the "new" keyword.
UIAutomation constants and enumerations are available from the UIA_Enum class (see a more thorough description at the class header).
Microsoft documentation for constants and enumerations:
UI Automation Constants: https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-entry-constants
UI Automation Enumerations: https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-entry-enumerations
For more information, see the AHK Forums post on UIAutomation: https://www.autohotkey.com/boards/viewtopic.php?f=6&t=104999
*/
/*
Questions:
- better way to do __properties?
- better way to do __properties for multiple versions of objects? (eg UIA_Element2 being and UIA_Element.__properties + UIA_Element2.__properties)
- if method returns a SafeArray, should we return a Wrapped SafeArray, Raw SafeArray, or AHK Array. Currently we return wrapped AHK arrays for SafeArrays. Although SafeArrays are more convenient to loop over, this causes more confusion in users who are not familiar with SafeArrays (questions such as why are they 0-indexed not 1-indexed, why doesnt for k, v in SafeArray work properly etc).
- on UIA Interface conversion methods, how should the data be returned? wrapped/extracted or raw? should raw data be a ByRef param?
- do variants need cleared? what about SysAllocString BSTRs? As per Microsoft documentation (https://docs.microsoft.com/en-us/cpp/atl-mfc-shared/allocating-and-releasing-memory-for-a-bstr?view=msvc-170), when we pass a BSTR into IUIAutomation, then IUIAutomation should take care of freeing it. But when we receive a UIA_Variant and use UIA_VariantData, then we should clear the BSTR.
- ObjRelease: if IUIA returns an interface then it automatically increases the ref count for the object it inherits from, and when released decreases it. So do all returned objects (UIA_Element, UIA_Pattern, UIA_TextRange) need to be released? Currently we release these objects as well, but jethrow's version didn't.
- do RECT structs need destroyed?
- if returning wrapped data & raw is ByRef, will the wrapped data being released destroy the raw data?
- returning variant data other than vt=3|8|9|13|0x2000
- Cached Members?
- UIA Element existance - dependent on window being visible (non minimized), and also sometimes Elements are lazily generated (eg Microsoft Teams, when a meeting is started then the toolbar buttons (eg Mute, react) aren't visible to UIA, but hovering over them with the cursor or calling ElementFromPoint causes Teams to generate and make them visible to UIA.
- better way of supporting differing versions of IUIAutomation (version 2, 3, 4)
- Get methods vs property getter: currently we use properties when the item stores data, fetching the data is "cheap" and when it doesn't have side-effects, and in computationally expensive cases use Get...().
*/
; Base class for all UIA objects (UIA_Interface, UIA_Element etc), that is used to fetch properties from __Properties, and get constants and enumerations from UIA_Enum.
class UIA_Base {
__New(p="", flag=0, version="") {
ObjInsert(this,"__Type","IUIAutomation" SubStr(this.__Class,5))
,ObjInsert(this,"__Value",p)
,ObjInsert(this,"__Flag",flag)
,ObjInsert(this,"__Version",version)
}
__Get(member) {
if member not in base,__UIA,TreeWalkerTrue,TrueCondition ; base & __UIA should act as normal
{
if raw:=SubStr(member,0)="*" ; return raw data - user should know what they are doing
member:=SubStr(member,1,-1)
if RegExMatch(this.__properties, "im)^" member ",(\d+),(\w+)", m) { ; if the member is in the properties. if not - give error message
if (m2="VARIANT") ; return VARIANT data - DllCall output param different
return UIA_Hr(DllCall(this.__Vt(m1), "ptr",this.__Value, "ptr",UIA_Variant(out)))? (raw?out:UIA_VariantData(out)):
else if (m2="RECT") ; return RECT struct - DllCall output param different
return UIA_Hr(DllCall(this.__Vt(m1), "ptr",this.__Value, "ptr",&(rect,VarSetCapacity(rect,16))))? (raw?out:UIA_RectToObject(rect)):
else if (m2="double")
return UIA_Hr(DllCall(this.__Vt(m1), "ptr",this.__Value, "Double*",out))?out:
else if UIA_Hr(DllCall(this.__Vt(m1), "ptr",this.__Value, "ptr*",out))
return raw?out:m2="BSTR"?StrGet(out) (DllCall("oleaut32\SysFreeString", "ptr", out)?"":""):RegExMatch(m2,"i)IUIAutomation\K\w+",n)?(IsFunc(n)?UIA_%n%(out):new UIA_%n%(out)):out ; Bool, int, DWORD, HWND, CONTROLTYPEID, OrientationType? if IUIAutomation___ is a function, that will be called first, if not then an object is created with the name
} else if ObjHasKey(UIA_Enum, member) {
return UIA_Enum[member]
} else if RegexMatch(member, "i)PatternId|EventId|PropertyId|AttributeId|ControlTypeId|AnnotationType|StyleId|LandmarkTypeId|HeadingLevel|ChangeId|MetadataId", match) {
return UIA_Enum["UIA_" match](member)
} else throw Exception("Property not supported by the " this.__Class " Class.",-1,member)
}
}
__Set(member) {
if !(member == "base")
throw Exception("Assigning values not supported by the " this.__Class " Class.",-1,member)
}
__Call(member, params*) {
if RegexMatch(member, "i)^(?:UIA_)?(PatternId|EventId|PropertyId|AttributeId|ControlTypeId|AnnotationType|StyleId|LandmarkTypeId|HeadingLevel|ChangeId|MetadataId)$", match) {
return UIA_Enum["UIA_" match1](params*)
} else if !ObjHasKey(UIA_Base,member)&&!ObjHasKey(this,member)&&!"_NewEnum"
throw Exception("Method Call not supported by the " this.__Class " Class.",-1,member)
}
__Delete() {
this.__Flag ? ObjRelease(this.__Value):
}
__Vt(n) {
return NumGet(NumGet(this.__Value+0,"ptr")+n*A_PtrSize,"ptr")
}
}
/*
Exposes methods that enable to discover, access, and filter UI Automation elements. UI Automation exposes every element of the UI Automation as an object represented by the IUIAutomation interface. The members of this interface are not specific to a particular element.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomation
*/
class UIA_Interface extends UIA_Base {
static __IID := "{30cbe57d-d9d0-452a-ab13-7ac5ac4825ee}"
, __properties := "ControlViewWalker,14,IUIAutomationTreeWalker`r`nContentViewWalker,15,IUIAutomationTreeWalker`r`nRawViewWalker,16,IUIAutomationTreeWalker`r`nRawViewCondition,17,IUIAutomationCondition`r`nControlViewCondition,18,IUIAutomationCondition`r`nContentViewCondition,19,IUIAutomationCondition`r`nProxyFactoryMapping,48,IUIAutomationProxyFactoryMapping`r`nReservedNotSupportedValue,54,IUnknown`r`nReservedMixedAttributeValue,55,IUnknown"
; Compares two UI Automation elements to determine whether they represent the same underlying UI element.
CompareElements(e1,e2) {
return UIA_Hr(DllCall(this.__Vt(3), "ptr",this.__Value, "ptr",e1.__Value, "ptr",e2.__Value, "int*",out))? out:
}
; Compares two integer arrays containing run-time identifiers (IDs) to determine whether their content is the same and they belong to the same UI element. r1 and r2 need to be RuntimeId arrays (returned by GetRuntimeId()), where array.base.__Value contains the corresponding safearray.
CompareRuntimeIds(r1,r2) {
return UIA_Hr(DllCall(this.__Vt(4), "ptr",this.__Value, "ptr",ComObjValue(r1.__Value), "ptr",ComObjValue(r2.__Value), "int*",out))? out:
}
; Retrieves the UI Automation element that represents the desktop.
GetRootElement() {
return UIA_Hr(DllCall(this.__Vt(5), "ptr",this.__Value, "ptr*",out))? UIA_Element(out):
}
; Retrieves a UI Automation element for the specified window. Additionally activateChromiumAccessibility flag can be set to True to send the WM_GETOBJECT message to Chromium-based apps to activate accessibility if it isn't activated.
ElementFromHandle(hwnd, activateChromiumAccessibility=False) {
if activateChromiumAccessibility {
WinGet, cList, ControlList, ahk_id %hwnd%
if InStr(cList, "Chrome_RenderWidgetHostHWND1")
SendMessage, WM_GETOBJECT := 0x003D, 0, 1, Chrome_RenderWidgetHostHWND1, ahk_id %hwnd%
}
return UIA_Hr(DllCall(this.__Vt(6), "ptr",this.__Value, "ptr",hwnd, "ptr*",out))? UIA_Element(out):
}
; Retrieves the UI Automation element at the specified point on the desktop. Additionally activateChromiumAccessibility flag can be set to True to send the WM_GETOBJECT message to Chromium-based apps to activate accessibility if it isn't activated.
ElementFromPoint(x="", y="", activateChromiumAccessibility=False) {
if (x==""||y=="")
DllCall("GetCursorPos","Int64*",pt)
if (activateChromiumAccessibility && (hwnd := DllCall("GetAncestor", "UInt", DllCall("WindowFromPoint", pt), "UInt", GA_ROOT := 2))) { ; hwnd from point by SKAN
WinGet, cList, ControlList, ahk_id %hwnd%
if InStr(cList, "Chrome_RenderWidgetHostHWND1")
SendMessage, WM_GETOBJECT := 0x003D, 0, 1, Chrome_RenderWidgetHostHWND1, ahk_id %hwnd%
}
return UIA_Hr(DllCall(this.__Vt(7), "ptr",this.__Value, "UInt64",x==""||y==""?pt:x&0xFFFFFFFF|(y&0xFFFFFFFF)<<32, "ptr*",out))? UIA_Element(out):
}
; Retrieves the UI Automation element that has the input focus.
GetFocusedElement() {
return UIA_Hr(DllCall(this.__Vt(8), "ptr",this.__Value, "ptr*",out))? UIA_Element(out):
}
; Retrieves the UI Automation element that represents the desktop, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
GetRootElementBuildCache(cacheRequest) { ; UNTESTED.
return UIA_Hr(DllCall(this.__Vt(9), "ptr",this.__Value, "ptr", cacheRequest.__Value, "ptr*",out))? UIA_Element(out):
}
; Retrieves a UI Automation element for the specified window, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
ElementFromHandleBuildCache(hwnd, cacheRequest) {
return UIA_Hr(DllCall(this.__Vt(10), "ptr",this.__Value, "ptr",hwnd, "ptr",cacheRequest.__Value, "ptr*",out))? UIA_Element(out):
}
; Retrieves the UI Automation element at the specified point on the desktop, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
ElementFromPointBuildCache(x="", y="", cacheRequest=0) { ; UNTESTED.
return UIA_Hr(DllCall(this.__Vt(11), "ptr",this.__Value, "UInt64",x==""||y==""?0*DllCall("GetCursorPos","Int64*",pt)+pt:x&0xFFFFFFFF|(y&0xFFFFFFFF)<<32, "ptr", cacheRequest.__Value, "ptr*",out))? UIA_Element(out):
}
; Retrieves the UI Automation element that has the input focus, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
GetFocusedElementBuildCache(cacheRequest) { ; UNTESTED.
return UIA_Hr(DllCall(this.__Vt(12), "ptr",this.__Value, "ptr", cacheRequest.__Value, "ptr*",out))? UIA_Element(out):
}
; Retrieves a UIA_TreeWalker object that can be used to traverse the Microsoft UI Automation tree.
CreateTreeWalker(condition) {
return UIA_Hr(DllCall(this.__Vt(13), "ptr",this.__Value, "ptr",Condition.__Value, "ptr*",out))? new UIA_TreeWalker(out):
}
CreateCacheRequest() {
return UIA_Hr(DllCall(this.__Vt(20), "ptr",this.__Value, "ptr*",out))? new UIA_CacheRequest(out):
}
; Creates a condition that is always true.
CreateTrueCondition() {
return UIA_Hr(DllCall(this.__Vt(21), "ptr",this.__Value, "ptr*",out))? new UIA_BoolCondition(out):
}
; Creates a condition that is always false.
CreateFalseCondition() {
return UIA_Hr(DllCall(this.__Vt(22), "ptr",this.__Value, "ptr*",out))? new UIA_BoolCondition(out):
}
; Creates a condition that selects elements that have a property with the specified value (var).
; If type is specified then a new variant is created with the specified variant type, otherwise the type is fetched from UIA_PropertyVariantType enums (so usually this can be left unchanged).
CreatePropertyCondition(propertyId, var, type="Variant") {
if (type!="Variant")
UIA_Variant(var,type,var)
else if (maybeVar := UIA_Enum.UIA_PropertyVariantType(propertyId)) {
UIA_Variant(var,maybeVar,var)
}
return UIA_Hr((A_PtrSize == 4) ? DllCall(this.__Vt(23), "ptr",this.__Value, "int",propertyId, "int64", NumGet(var, 0, "int64"), "int64", NumGet(var, 8, "int64"), "ptr*",out) : DllCall(this.__Vt(23), "ptr",this.__Value, "int",propertyId, "ptr",&var, "ptr*",out))? new UIA_PropertyCondition(out):
}
; Creates a condition that selects elements that have a property with the specified value (var), using optional flags. If type is specified then a new variant is created with the specified variant type, otherwise the type is fetched from UIA_PropertyVariantType enums (so usually this can be left unchanged). flags can be one of PropertyConditionFlags, default is PropertyConditionFlags_IgnoreCase = 0x1.
CreatePropertyConditionEx(propertyId, var, type="Variant", flags=0x1) {
if (type!="Variant")
UIA_Variant(var,type,var)
else if (maybeVar := UIA_Enum.UIA_PropertyVariantType(propertyId)) {
UIA_Variant(var,maybeVar,var)
}
return UIA_Hr((A_PtrSize == 4) ? DllCall(this.__Vt(24), "ptr",this.__Value, "int",propertyId, "int64", NumGet(var, 0, "int64"), "int64", NumGet(var, 8, "int64"), "uint",flags, "ptr*",out) : DllCall(this.__Vt(24), "ptr",this.__Value, "int",propertyId, "ptr",&var, "uint",flags, "ptr*",out))? new UIA_PropertyCondition(out):
}
; Creates a condition that selects elements that match both of two conditions.
CreateAndCondition(c1,c2) {
return UIA_Hr(DllCall(this.__Vt(25), "ptr",this.__Value, "ptr",c1.__Value, "ptr",c2.__Value, "ptr*",out))? new UIA_AndCondition(out):
}
; Creates a condition that selects elements based on multiple conditions, all of which must be true.
CreateAndConditionFromArray(array) {
;->in: AHK Array or Wrapped SafeArray
if ComObjValue(array)&0x2000
SafeArray:=array
else {
SafeArray:=ComObj(0x2003,DllCall("oleaut32\SafeArrayCreateVector", "uint",13, "uint",0, "uint",array.MaxIndex()),1)
for i,c in array
SafeArray[A_Index-1]:=c.__Value, ObjAddRef(c.__Value) ; AddRef - SafeArrayDestroy will release UIA_Conditions - they also release themselves
}
return UIA_Hr(DllCall(this.__Vt(26), "ptr",this.__Value, "ptr",ComObjValue(SafeArray), "ptr*",out))? new UIA_AndCondition(out):
}
; Creates a condition that selects elements from a native array, based on multiple conditions that must all be true
CreateAndConditionFromNativeArray(conditions, conditionCount) { ; UNTESTED.
/* [in] IUIAutomationCondition **conditions,
[in] int conditionCount,
[out, retval] IUIAutomationCondition **newCondition
*/
return UIA_Hr(DllCall(this.__Vt(27), "ptr",this.__Value, "ptr", conditions, "int", conditionCount, "ptr*",out))? new UIA_AndCondition(out):
}
; Creates a combination of two conditions where a match exists if either of the conditions is true.
CreateOrCondition(c1,c2) {
return UIA_Hr(DllCall(this.__Vt(28), "ptr",this.__Value, "ptr",c1.__Value, "ptr",c2.__Value, "ptr*",out))? new UIA_OrCondition(out):
}
; Creates a combination of two or more conditions where a match exists if any of the conditions is true.
CreateOrConditionFromArray(array) {
;->in: AHK Array or Wrapped SafeArray
if ComObjValue(array)&0x2000
SafeArray:=array
else {
SafeArray:=ComObj(0x2003,DllCall("oleaut32\SafeArrayCreateVector", "uint",13, "uint",0, "uint",array.MaxIndex()),1)
for i,c in array
SafeArray[A_Index-1]:=c.__Value, ObjAddRef(c.__Value) ; AddRef - SafeArrayDestroy will release UIA_Conditions - they also release themselves
}
return UIA_Hr(DllCall(this.__Vt(29), "ptr",this.__Value, "ptr",ComObjValue(SafeArray), "ptr*",out))? new UIA_OrCondition(out):
}
CreateOrConditionFromNativeArray(p*) { ; Not Implemented
return UIA_Hr(DllCall(this.__Vt(30), "ptr",this.__Value, "ptr",conditions, "int", conditionCount, "ptr*",out))? new UIA_OrCondition(out):
/* [in] IUIAutomationCondition **conditions,
[in] int conditionCount,
[out, retval] IUIAutomationCondition **newCondition
*/
}
; Creates a condition that is the negative of a specified condition.
CreateNotCondition(c) {
return UIA_Hr(DllCall(this.__Vt(31), "ptr",this.__Value, "ptr",c.__Value, "ptr*",out))? new UIA_NotCondition(out):
}
; Registers a method that handles Microsoft UI Automation events. eventId must be an EventId enum. scope must be a TreeScope enum. cacheRequest can be specified is caching is used. handler is an event handler object, which can be created with UIA_CreateEventHandler function.
AddAutomationEventHandler(eventId, element, scope=0x4, cacheRequest=0, handler="") {
return UIA_Hr(DllCall(this.__Vt(32), "ptr",this.__Value, "int", eventId, "ptr", element.__Value, "uint", scope, "ptr",cacheRequest.__Value,"ptr",handler.__Value))
}
; Removes the specified UI Automation event handler.
RemoveAutomationEventHandler(eventId, element, handler) {
return UIA_Hr(DllCall(this.__Vt(33), "ptr",this.__Value, "int", eventId, "ptr", element.__Value, "ptr",handler.__Value))
}
;~ AddPropertyChangedEventHandlerNativeArray 34
; Registers a method that handles an array of property-changed events
AddPropertyChangedEventHandler(element,scope=0x1,cacheRequest=0,handler="",propertyArray="") {
SafeArray:=ComObjArray(0x3,propertyArray.MaxIndex())
for i,propertyId in propertyArray
SafeArray[i-1]:=propertyId
return UIA_Hr(DllCall(this.__Vt(35), "ptr",this.__Value, "ptr",element.__Value, "int",scope, "ptr",cacheRequest.__Value,"ptr",handler.__Value,"ptr",ComObjValue(SafeArray)))
}
RemovePropertyChangedEventHandler(element, handler) {
return UIA_Hr(DllCall(this.__Vt(36), "ptr",this.__Value, "ptr",element.__Value, "ptr", handler.__Value))
}
AddStructureChangedEventHandler(element, handler) { ; UNTESTED.
return UIA_Hr(DllCall(this.__Vt(37), "ptr",this.__Value, "ptr",element.__Value, "ptr",handler.__Value))
}
RemoveStructureChangedEventHandler(element, handler) { ; UNTESTED
return UIA_Hr(DllCall(this.__Vt(38), "ptr",this.__Value, "ptr", element.__Value, "ptr",handler.__Value))
}
; Registers a method that handles ChangedEvent events. handler is required, cacheRequest can be left to 0
AddFocusChangedEventHandler(handler, cacheRequest=0) {
return UIA_Hr(DllCall(this.__Vt(39), "ptr",this.__Value, "ptr",cacheRequest.__Value, "ptr",handler.__Value))
}
RemoveFocusChangedEventHandler(handler) {
return UIA_Hr(DllCall(this.__Vt(40), "ptr",this.__Value, "ptr",handler.__Value))
}
RemoveAllEventHandlers() {
return UIA_Hr(DllCall(this.__Vt(41), "ptr",this.__Value))
}
IntNativeArrayToSafeArray(ByRef nArr, n="") {
return UIA_Hr(DllCall(this.__Vt(42), "ptr",this.__Value, "ptr",&nArr, "int",n?n:VarSetCapacity(nArr)/4, "ptr*",out))? ComObj(0x2003,out,1):
}
IntSafeArrayToNativeArray(sArr, Byref nArr, Byref arrayCount) { ; NOT WORKING
VarSetCapacity(nArr,(sArr.MaxIndex()+1)*A_PtrSize)
return UIA_Hr(DllCall(this.__Vt(43), "ptr",this.__Value, "ptr",ComObjValue(sArr), "ptr*",nArr, "int*",arrayCount))? nArr:
}
RectToVariant(ByRef rect, ByRef out="") { ; in:{left,top,right,bottom} ; out:(left,top,width,height)
; in: RECT Struct
; out: AHK Wrapped SafeArray & ByRef Variant
return UIA_Hr(DllCall(this.__Vt(44), "ptr",this.__Value, "ptr",&rect, "ptr",UIA_Variant(out)))? UIA_VariantData(out):
}
VariantToRect(ByRef var, ByRef rect="") { ; NOT WORKING
; in: VT_VARIANT (SafeArray)
; out: AHK Wrapped RECT Struct & ByRef Struct
VarSetCapacity(rect,16)
return UIA_Hr(DllCall(this.__Vt(45), "ptr",this.__Value, "ptr",var, "ptr*",rect))? UIA_RectToObject(rect):
}
;~ SafeArrayToRectNativeArray 46
;~ CreateProxyFactoryEntry 47
; Retrieves the registered programmatic name of a property. Intended for debugging and diagnostic purposes only. The string is not localized.
GetPropertyProgrammaticName(Id) {
return UIA_Hr(DllCall(this.__Vt(49), "ptr",this.__Value, "int",Id, "ptr*",out))? StrGet(out) (DllCall("oleaut32\SysFreeString", "ptr", out)?"":""):
}
; Retrieves the registered programmatic name of a control pattern. Intended for debugging and diagnostic purposes only. The string is not localized.
GetPatternProgrammaticName(Id) {
return UIA_Hr(DllCall(this.__Vt(50), "ptr",this.__Value, "int",Id, "ptr*",out))? StrGet(out):
}
; Returns an object where keys are the names and values are the Ids
PollForPotentialSupportedPatterns(e, Byref Ids="", Byref Names="") {
return UIA_Hr(DllCall(this.__Vt(51), "ptr",this.__Value, "ptr",e.__Value, "ptr*",Ids, "ptr*",Names))? UIA_SafeArraysToObject(Names:=ComObj(0x2008,Names,1),Ids:=ComObj(0x2003,Ids,1)): ; These SafeArrays are wrapped by ComObj, so they will automatically be released
}
PollForPotentialSupportedProperties(e, Byref Ids="", Byref Names="") {
return UIA_Hr(DllCall(this.__Vt(52), "ptr",this.__Value, "ptr",e.__Value, "ptr*",Ids, "ptr*",Names))? UIA_SafeArraysToObject(Names:=ComObj(0x2008,Names,1),Ids:=ComObj(0x2003,Ids,1)):
}
CheckNotSupported(value) { ; Useless in this Framework???
/* Checks a provided VARIANT to see if it contains the Not Supported identifier.
After retrieving a property for a UI Automation element, call this method to determine whether the element supports the
retrieved property. CheckNotSupported is typically called after calling a property retrieving method such as GetCurrentPropertyValue.
*/
return UIA_Hr(DllCall(this.__Vt(53), "ptr",this.__Value, "ptr",value, "int*",out))? out:
}
;~ ReservedNotSupportedValue 54
;~ ReservedMixedAttributeValue 55
ElementFromIAccessible(IAcc, childId=0) {
/* The method returns E_INVALIDARG - "One or more arguments are not valid" - if the underlying implementation of the
Microsoft UI Automation element is not a native Microsoft Active Accessibility server; that is, if a client attempts to retrieve
the IAccessible interface for an element originally supported by a proxy object from Oleacc.dll, or by the UIA-to-MSAA Bridge.
*/
return UIA_Hr(DllCall(this.__Vt(56), "ptr",this.__Value, "ptr",ComObjValue(IAcc), "int",childId, "ptr*",out))? UIA_Element(out):
}
ElementFromIAccessibleBuildCache(IAcc, childId, cacheRequest) {
return UIA_Hr(DllCall(this.__Vt(57), "ptr",this.__Value, "ptr",ComObjValue(IAcc), "int",childId, "ptr", cacheRequest.__Value, "ptr*",out))? UIA_Element(out):
}
; ------- ONLY CUSTOM FUNCTIONS FROM HERE ON ----------------
/*
CreateCondition is a wrapper for CreatePropertyConditionEx.
Property can be the PropertyId, or (partial) name (eg 30000 == "ControlType" == "ControlTypePropertyId").
Similarly the value can be the id or (partial) name.
Flags: 0=no flags; 1=ignore case; 2=match substring; 3=ignore case and match substring
*/
CreateCondition(property, val, flags=0) {
if !RegexMatch(property, "^\d+$")
RegexMatch(property, "(?:UIA_)?\K.+?(?=(Id)?PropertyId|$)", property), propCond := UIA_Enum.UIA_PropertyId(property), property := StrReplace(StrReplace(property, "AnnotationAnnotation", "Annotation"), "StylesStyle", "Style")
else
propCond := property
if RegexMatch(val, "^\w+$") {
val := IsFunc("UIA_Enum.UIA_" property "Id") ? UIA_Enum["UIA_" property "Id"](val) : IsFunc("UIA_Enum.UIA_" property) ? UIA_Enum["UIA_" property](val) : val
}
if (propCond && val)
return this.CreatePropertyConditionEx(propCond, val,, flags)
}
; Gets ElementFromPoint and filters out the smallest subelement that is under the specified point. If windowEl (window under the point) is provided, then a deep search is performed for the smallest element (this might be very slow in large trees).
SmallestElementFromPoint(x="", y="", activateChromiumAccessibility=False, windowEl="") {
;ToolTip, % "starting" IsObject(winEl)
if IsObject(windowEl) {
element := this.ElementFromPoint(x, y, activateChromiumAccessibility)
bound := element.CurrentBoundingRectangle, elementSize := (bound.r-bound.l)*(bound.b-bound.t), prevElementSize := 0, stack := [windowEl]
Loop
{
bound := stack[1].CurrentBoundingRectangle
if ((x >= bound.l) && (x <= bound.r) && (y >= bound.t) && (y <= bound.b)) { ; If parent is not in bounds, then children arent either
if ((newSize := (bound.r-bound.l)*(bound.b-bound.t)) < elementSize)
element := stack[1], elementSize := newSize
for _, childEl in stack[1].GetChildren() {
bound := childEl.CurrentBoundingRectangle
if ((x >= bound.l) && (x <= bound.r) && (y >= bound.t) && (y <= bound.b)) {
stack.Push(childEl)
if ((newSize := (bound.r-bound.l)*(bound.b-bound.t)) < elementSize)
elementSize := newSize, element := childEl
}
}
}
stack.RemoveAt(1)
} Until !stack.MaxIndex()
return element
} else {
element := this.ElementFromPoint(x, y, activateChromiumAccessibility)
bound := element.CurrentBoundingRectangle, elementSize := (bound.r-bound.l)*(bound.b-bound.t), prevElementSize := 0
for k, v in element.FindAll(this.__UIA.TrueCondition) {
bound := v.CurrentBoundingRectangle
if ((x >= bound.l) && (x <= bound.r) && (y >= bound.t) && (y <= bound.b) && ((newSize := (bound.r-bound.l)*(bound.b-bound.t)) < elementSize))
element := v, elementSize := newSize
}
return element
}
}
}
class UIA_Interface2 extends UIA_Interface {
static __IID := "{34723aff-0c9d-49d0-9896-7ab52df8cd8a}"
, __Properties := UIA_Interface.__Properties
; Specifies whether calls to UI Automation control pattern methods automatically set focus to the target element. Default is True.
AutoSetFocus[]
{
get {
return UIA_Hr(DllCall(this.__Vt(58), "ptr",this.__Value, "ptr*", out))?out:
}
set {
return UIA_Hr(DllCall(this.__Vt(59), "ptr",this.__Value, "int", value))
}
}
; Specifies the length of time that UI Automation will wait for a provider to respond to a client request for an automation element. Default is 20000ms (20 seconds), minimum seems to be 50ms.
ConnectionTimeout[]
{
get {
return UIA_Hr(DllCall(this.__Vt(60), "ptr",this.__Value, "ptr*", out))?out:
}
set {
return UIA_Hr(DllCall(this.__Vt(61), "ptr",this.__Value, "int", value)) ; Minimum seems to be 50 (ms?)
}
}
; Specifies the length of time that UI Automation will wait for a provider to respond to a client request for information about an automation element. Default is 2000ms (2 seconds), minimum seems to be 50ms.
TransactionTimeout[]
{
get {
return UIA_Hr(DllCall(this.__Vt(62), "ptr",this.__Value, "ptr*", out))?out:
}
set {
return UIA_Hr(DllCall(this.__Vt(63), "ptr",this.__Value, "int", value))
}
}
}
class UIA_Interface3 extends UIA_Interface2 { ; UNTESTED
static __IID := "{73d768da-9b51-4b89-936e-c209290973e7}"
, __Properties := UIA_Interface2.__Properties
AddTextEditTextChangedEventHandler(element, scope, textEditChangeType, cacheRequest=0, handler="") {
return UIA_Hr(DllCall(this.__Vt(64), "ptr",this.__Value, "ptr", element.__Value, "int", scope, "int", textEditChangeType, "ptr", cacheRequest.__Value, "ptr", handler.__Value))
}
RemoveTextEditTextChangedEventHandler(element, handler) {
return UIA_Hr(DllCall(this.__Vt(65), "ptr",this.__Value, "ptr", element.__Value, "ptr", handler.__Value))
}
}
class UIA_Interface4 extends UIA_Interface3 { ; UNTESTED
static __IID := "{1189c02a-05f8-4319-8e21-e817e3db2860}"
, __Properties := UIA_Interface3.__Properties
AddChangesEventHandler(element, scope, changeTypes, changesCount, cacheRequest=0, handler="") {
return UIA_Hr(DllCall(this.__Vt(66), "ptr",this.__Value, "ptr", element.__Value, "int", scope, "int", changeTypes, "int", changesCount, "ptr", cacheRequest.__Value, "ptr", handler.__Value))
}
RemoveChangesEventHandler(element, handler) {
return UIA_Hr(DllCall(this.__Vt(67), "ptr",this.__Value, "ptr", element.__Value, "ptr", handler.__Value))
}
}
class UIA_Interface5 extends UIA_Interface4 { ; UNTESTED
static __IID := "{25f700c8-d816-4057-a9dc-3cbdee77e256}"
, __Properties := UIA_Interface4.__Properties
AddNotificationEventHandler(element, scope, cacheRequest, handler) {
return UIA_Hr(DllCall(this.__Vt(68), "ptr",this.__Value, "ptr", element.__Value, "int", scope, "ptr", cacheRequest.__Value, "ptr", handler.__Value))
}
RemoveNotificationEventHandler(element, handler) {
return UIA_Hr(DllCall(this.__Vt(69), "ptr",this.__Value, "ptr", element.__Value, "ptr", handler.__Value))
}
}
class UIA_Interface6 extends UIA_Interface5 { ; NOT IMPLEMENTED
static __IID := "{aae072da-29e3-413d-87a7-192dbf81ed10}"
, __Properties := UIA_Interface5.__Properties
/*
#define IUIAutomation6_CreateEventHandlerGroup(This,handlerGroup) \
( (This)->lpVtbl -> CreateEventHandlerGroup(This,handlerGroup) )
#define IUIAutomation6_AddEventHandlerGroup(This,element,handlerGroup) \
( (This)->lpVtbl -> AddEventHandlerGroup(This,element,handlerGroup) )
#define IUIAutomation6_RemoveEventHandlerGroup(This,element,handlerGroup) \
( (This)->lpVtbl -> RemoveEventHandlerGroup(This,element,handlerGroup) )
#define IUIAutomation6_get_ConnectionRecoveryBehavior(This,connectionRecoveryBehaviorOptions) \
( (This)->lpVtbl -> get_ConnectionRecoveryBehavior(This,connectionRecoveryBehaviorOptions) )
#define IUIAutomation6_put_ConnectionRecoveryBehavior(This,connectionRecoveryBehaviorOptions) \
( (This)->lpVtbl -> put_ConnectionRecoveryBehavior(This,connectionRecoveryBehaviorOptions) )
#define IUIAutomation6_get_CoalesceEvents(This,coalesceEventsOptions) \
( (This)->lpVtbl -> get_CoalesceEvents(This,coalesceEventsOptions) )
#define IUIAutomation6_put_CoalesceEvents(This,coalesceEventsOptions) \
( (This)->lpVtbl -> put_CoalesceEvents(This,coalesceEventsOptions) )
#define IUIAutomation6_AddActiveTextPositionChangedEventHandler(This,element,scope,cacheRequest,handler) \
( (This)->lpVtbl -> AddActiveTextPositionChangedEventHandler(This,element,scope,cacheRequest,handler) )
#define IUIAutomation6_RemoveActiveTextPositionChangedEventHandler(This,element,handler) \
( (This)->lpVtbl -> RemoveActiveTextPositionChangedEventHandler(This,element,handler) )
*/
}
class UIA_Interface7 extends UIA_Interface6 {
static __IID := "{29de312e-83c6-4309-8808-e8dfcb46c3c2}"
, __Properties := UIA_Interface6.__Properties
}
/*
Exposes methods and properties for a UI Automation element, which represents a UI item.
Microsoft documentation: https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationelement
*/
class UIA_Element extends UIA_Base {
;~ http://msdn.microsoft.com/en-us/library/windows/desktop/ee671425(v=vs.85).aspx
static __IID := "{d22108aa-8ac5-49a5-837b-37bbb3d7591e}"
, __properties := "CurrentProcessId,20,int`r`nCurrentControlType,21,CONTROLTYPEID`r`nCurrentLocalizedControlType,22,BSTR`r`nCurrentName,23,BSTR`r`nCurrentAcceleratorKey,24,BSTR`r`nCurrentAccessKey,25,BSTR`r`nCurrentHasKeyboardFocus,26,BOOL`r`nCurrentIsKeyboardFocusable,27,BOOL`r`nCurrentIsEnabled,28,BOOL`r`nCurrentAutomationId,29,BSTR`r`nCurrentClassName,30,BSTR`r`nCurrentHelpText,31,BSTR`r`nCurrentCulture,32,int`r`nCurrentIsControlElement,33,BOOL`r`nCurrentIsContentElement,34,BOOL`r`nCurrentIsPassword,35,BOOL`r`nCurrentNativeWindowHandle,36,UIA_HWND`r`nCurrentItemType,37,BSTR`r`nCurrentIsOffscreen,38,BOOL`r`nCurrentOrientation,39,OrientationType`r`nCurrentFrameworkId,40,BSTR`r`nCurrentIsRequiredForForm,41,BOOL`r`nCurrentItemStatus,42,BSTR`r`nCurrentBoundingRectangle,43,RECT`r`nCurrentLabeledBy,44,IUIAutomationElement`r`nCurrentAriaRole,45,BSTR`r`nCurrentAriaProperties,46,BSTR`r`nCurrentIsDataValidForForm,47,BOOL`r`nCurrentControllerFor,48,IUIAutomationElementArray`r`nCurrentDescribedBy,49,IUIAutomationElementArray`r`nCurrentFlowsTo,50,IUIAutomationElementArray`r`nCurrentProviderDescription,51,BSTR`r`nCachedProcessId,52,int`r`nCachedControlType,53,CONTROLTYPEID`r`nCachedLocalizedControlType,54,BSTR`r`nCachedName,55,BSTR`r`nCachedAcceleratorKey,56,BSTR`r`nCachedAccessKey,57,BSTR`r`nCachedHasKeyboardFocus,58,BOOL`r`nCachedIsKeyboardFocusable,59,BOOL`r`nCachedIsEnabled,60,BOOL`r`nCachedAutomationId,61,BSTR`r`nCachedClassName,62,BSTR`r`nCachedHelpText,63,BSTR`r`nCachedCulture,64,int`r`nCachedIsControlElement,65,BOOL`r`nCachedIsContentElement,66,BOOL`r`nCachedIsPassword,67,BOOL`r`nCachedNativeWindowHandle,68,UIA_HWND`r`nCachedItemType,69,BSTR`r`nCachedIsOffscreen,70,BOOL`r`nCachedOrientation,71,OrientationType`r`nCachedFrameworkId,72,BSTR`r`nCachedIsRequiredForForm,73,BOOL`r`nCachedItemStatus,74,BSTR`r`nCachedBoundingRectangle,75,RECT`r`nCachedLabeledBy,76,IUIAutomationElement`r`nCachedAriaRole,77,BSTR`r`nCachedAriaProperties,78,BSTR`r`nCachedIsDataValidForForm,79,BOOL`r`nCachedControllerFor,80,IUIAutomationElementArray`r`nCachedDescribedBy,81,IUIAutomationElementArray`r`nCachedFlowsTo,82,IUIAutomationElementArray`r`nCachedProviderDescription,83,BSTR"
SetFocus() {
return UIA_Hr(DllCall(this.__Vt(3), "ptr",this.__Value))
}
; Retrieves the unique identifier assigned to the UI element. The identifier is only guaranteed to be unique to the UI of the desktop on which it was generated. Identifiers can be reused over time.
GetRuntimeId() {
return UIA_Hr(DllCall(this.__Vt(4), "ptr",this.__Value, "ptr*",sa))? UIA_SafeArrayToAHKArray(ComObj(0x2003,sa,1)):
}
; Retrieves the first child or descendant element that matches the specified condition. scope must be one of TreeScope enums (default is TreeScope_Descendants := 0x4).
FindFirst(c="", scope=0x4) {
return UIA_Hr(DllCall(this.__Vt(5), "ptr",this.__Value, "uint",scope, "ptr",(c=""?this.TrueCondition:c).__Value, "ptr*",out))&&out? UIA_Element(out):
}
; Returns all UI Automation elements that satisfy the specified condition. scope must be one of TreeScope enums (default is TreeScope_Descendants := 0x4).
FindAll(c="", scope=0x4) {
return UIA_Hr(DllCall(this.__Vt(6), "ptr",this.__Value, "uint",scope, "ptr",(c=""?this.TrueCondition:c).__Value, "ptr*",out))&&out? UIA_ElementArray(out):
}
; Retrieves the first child or descendant element that matches the specified condition, prefetches the requested properties and control patterns, and stores the prefetched items in the cache
FindFirstBuildCache(c="", scope=0x4, cacheRequest="") { ; UNTESTED.
return UIA_Hr(DllCall(this.__Vt(7), "ptr",this.__Value, "uint",scope, "ptr",(c=""?this.TrueCondition:c).__Value, "ptr",cacheRequest.__Value, "ptr*",out))? UIA_Element(out):
}
; Returns all UI Automation elements that satisfy the specified condition, prefetches the requested properties and control patterns, and stores the prefetched items in the cache.
FindAllBuildCache(c="", scope=0x4, cacheRequest="") { ; UNTESTED.
return UIA_Hr(DllCall(this.__Vt(8), "ptr",this.__Value, "uint",scope, "ptr",(c=""?this.TrueCondition:c).__Value, "ptr",cacheRequest.__Value, "ptr*",out))? UIA_ElementArray(out):
}
; Retrieves a new UI Automation element with an updated cache.
BuildUpdatedCache(cacheRequest) { ; UNTESTED.
return UIA_Hr(DllCall(this.__Vt(9), "ptr",this.__Value, "ptr", cacheRequest.__Value, "ptr*",out))? UIA_Element(out):
}
; Retrieves the current value of a property for this element. "out" will be set to the raw variant (generally not used).
GetCurrentPropertyValue(propertyId, ByRef out="") {
if propertyId is not integer
propertyId := UIA_Enum.UIA_PropertyId(propertyId)
return UIA_Hr(DllCall(this.__Vt(10), "ptr",this.__Value, "uint", propertyId, "ptr",UIA_Variant(out)))? UIA_VariantData(out):
}
; Retrieves a property value for this element, optionally ignoring any default value. Passing FALSE in the ignoreDefaultValue parameter is equivalent to calling GetCurrentPropertyValue
GetCurrentPropertyValueEx(propertyId, ignoreDefaultValue=1, ByRef out="") {
if propertyId is not integer
propertyId := UIA_Enum.UIA_PropertyId(propertyId)
return UIA_Hr(DllCall(this.__Vt(11), "ptr",this.__Value, "uint",propertyId, "uint",ignoreDefaultValue, "ptr",UIA_Variant(out)))? UIA_VariantData(out):
}
; Retrieves a property value from the cache for this element.
GetCachedPropertyValue(propertyId, ByRef out="") { ; UNTESTED.
if propertyId is not integer
propertyId := UIA_Enum.UIA_PropertyId(propertyId)
return UIA_Hr(DllCall(this.__Vt(12), "ptr",this.__Value, "uint",propertyId, "ptr",UIA_Variant(out)))? UIA_VariantData(out):
}
; Retrieves a property value from the cache for this element, optionally ignoring any default value. Passing FALSE in the ignoreDefaultValue parameter is equivalent to calling GetCachedPropertyValue
GetCachedPropertyValueEx(propertyId, ignoreDefaultValue=1, ByRef out="") {
if propertyId is not integer
propertyId := UIA_Enum.UIA_PropertyId(propertyId)
return UIA_Hr(DllCall(this.__Vt(13), "ptr",this.__Value, "uint",propertyId, "uint",ignoreDefaultValue, "ptr",UIA_Variant(out)))? UIA_VariantData(out):
}
; Retrieves a UIA_Pattern object of the specified control pattern on this element. If a full pattern name is specified then that exact version will be used (eg "TextPattern" will return a UIA_TextPattern object), otherwise the highest version will be used (eg "Text" might return UIA_TextPattern2 if it is available). usedPattern will be set to the actual string used to look for the pattern (used mostly for debugging purposes)
GetCurrentPatternAs(pattern="", ByRef usedPattern="") {
if (InStr(usedPattern:=pattern, "Pattern")||(usedPattern := UIA_Pattern(pattern, this)))
return UIA_Hr(DllCall(this.__Vt(14), "ptr",this.__Value, "int",UIA_%usedPattern%.__PatternId, "ptr",UIA_GUID(riid,UIA_%usedPattern%.__iid), "ptr*",out)) ? new UIA_%usedPattern%(out,1):
else throw Exception("Pattern not implemented.",-1, "UIA_" pattern "Pattern")
}
; Retrieves a UIA_Pattern object of the specified control pattern on this element from the cache of this element.
GetCachedPatternAs(pattern="", ByRef usedPattern="") {
if (InStr(usedPattern:=pattern, "Pattern")||(usedPattern := UIA_Pattern(pattern, this)))
return UIA_Hr(DllCall(this.__Vt(15), "ptr",this.__Value, "int",UIA_%usedPattern%.__PatternId, "ptr",UIA_GUID(riid,UIA_%usedPattern%.__iid), "ptr*",out)) ? new UIA_%usedPattern%(out,1):
else throw Exception("Pattern not implemented.",-1, "UIA_" pattern "Pattern")
}
GetCurrentPattern(pattern, ByRef usedPattern="") {
; I don't know the difference between this and GetCurrentPatternAs
if (InStr(usedPattern:=pattern, "Pattern")||(usedPattern := UIA_Pattern(pattern, this)))
return UIA_Hr(DllCall(this.__Vt(16), "ptr",this.__Value, "int",UIA_%usedPattern%.__PatternId, "ptr*",out)) ? new UIA_%usedPattern%(out,1):
else throw Exception("Pattern not implemented.",-1, "UIA_" pattern "Pattern")
}
GetCachedPattern(patternId, ByRef usedPattern="") {
; I don't know the difference between this and GetCachedPatternAs
if (InStr(usedPattern:=pattern, "Pattern")||(usedPattern := UIA_Pattern(pattern, this)))
return UIA_Hr(DllCall(this.__Vt(17), "ptr",this.__Value, "int", UIA_%usedPattern%.__PatternId, "ptr*",out)) ? new UIA_%usedPattern%(out,1):
else throw Exception("Pattern not implemented.",-1, "UIA_" pattern "Pattern")
}
; Retrieves from the cache the parent of this UI Automation element
GetCachedParent() {
return UIA_Hr(DllCall(this.__Vt(18), "ptr",this.__Value, "ptr*",out))&&out? UIA_Element(out):
}
; Retrieves the cached child elements of this UI Automation element
GetCachedChildren() { ; UNTESTED.
return UIA_Hr(DllCall(this.__Vt(19), "ptr",this.__Value, "ptr*",out))&&out? UIA_ElementArray(out):
}
; Retrieves the physical screen coordinates of a point on the element that can be clicked
GetClickablePoint() {
UIA_Hr(DllCall(this.__Vt(84), "ptr",this.__Value, "ptr", &(point,VarSetCapacity(point,8)), "ptr*", out))&&out? {x:NumGet(point,0,"int"), y:NumGet(point,4,"int")}:
}
; ------- ONLY CUSTOM FUNCTIONS FROM HERE ON ----------------
; Gets or sets the current value of the element. Getter is a wrapper for GetCurrentPropertyValue("Value"), setter a wrapper for SetValue
CurrentValue[] {
get {
return this.GetCurrentPropertyValue("Value")
}
set {
return this.SetValue(value)
}
}
CurrentExists[] {
get {
try {
if ((val := this.CurrentName this.CurrentValue (this.CurrentBoundingRectangle.t ? 1 : "")) == "")
return 0
}
return 1
}
}
; Wait until the element doesn't exist, with a default timeOut of 10000ms (10 seconds). Returns 1 if the element doesn't exist, otherwise 0.
WaitNotExist(timeOut=10000) {
startTime := A_TickCount
while ((exists := this.CurrentExists) && ((timeOut < 1) ? 1 : (A_tickCount - startTime < timeOut)))
Sleep, 100
return !exists
}
; Wrapper for GetClickablePoint(), where additionally the coordinates are converted to relative coordinates. relativeTo can be window, screen or client, default is A_CoordModeMouse
GetClickablePointRelativeTo(relativeTo="") {
res := this.GetClickablePoint()
relativeTo := (relativeTo == "") ? A_CoordModeMouse : relativeTo
StringLower, relativeTo, relativeTo
if (relativeTo == "screen")
return res
else {
hwnd := this.GetParentHwnd()
if ((relativeTo == "window") || (relativeTo == "relative")) {
VarSetCapacity(RECT, 16)
DllCall("user32\GetWindowRect", "Ptr", hwnd, "Ptr", &RECT)
return {x:(res.x-NumGet(&RECT, 0, "Int")), y:(res.y-NumGet(&RECT, 4, "Int"))}
} else if (relativeTo == "client") {
VarSetCapacity(pt,8,0), NumPut(res.x,&pt,0,"int"), NumPut(res.y,&pt,4,"int")
DllCall("ScreenToClient", "Ptr",hwnd, "Ptr",&pt)
return {x:NumGet(pt,"int"), y:NumGet(pt,4,"int")}
}
}
}
; Get all available patterns for the element. Use of this should be avoided, since it calls GetCurrentPatternAs for every possible pattern. A better option is PollForPotentialSupportedPatterns.
GetSupportedPatterns() {
result := []
patterns := "Invoke,Selection,Value,RangeValue,Scroll,ExpandCollapse,Grid,GridItem,MultipleView,Window,SelectionItem,Dock,Table,TableItem,Text,Toggle,Transform,ScrollItem,ItemContainer,VirtualizedItem,SyncronizedInput,LegacyIAccessible"
Loop, Parse, patterns, `,
{
try {
if this.GetCurrentPropertyValue(UIA_Enum.UIA_PropertyId("Is" A_LoopField "PatternAvailable")) {
result.Push(A_LoopField)
}
}
}
return result
}
; Get the parent window hwnd from the element
GetParentHwnd() {
hwndNotZeroCond := this.__UIA.CreateNotCondition(this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_PropertyId("NativeWindowHandle"), 0)) ; create a condition to find NativeWindowHandlePropertyId of not 0
TW := this.__UIA.CreateTreeWalker(hwndNotZeroCond)
try {
hwnd := TW.NormalizeElement(this).GetCurrentPropertyValue(UIA_Enum.UIA_PropertyId("NativeWindowHandle"))
return hwndRoot := DllCall("user32\GetAncestor", Ptr,hwnd, UInt,2, Ptr)
} catch {
return 0
}
}
; Set element value using Value pattern, or as a fall-back using LegacyIAccessible pattern. If a pattern is specified then that is used instead. Alternatively CurrentValue property can be used to set the value.
SetValue(val, pattern="") {
if !pattern {
try {
this.GetCurrentPatternAs("Value").SetValue(val)
} catch {
this.GetCurrentPatternAs("LegacyIAccessible").SetValue(val)
}
} else {
this.GetCurrentPatternAs(pattern).SetValue(val)
}
}
; Click using one of the available click-like methods (InvokePattern Invoke(), TogglePattern Toggle(), ExpandCollapsePattern Expand() or Collapse() (depending on the state of the element), SelectionItemPattern Select(), or LegacyIAccessible DoDefaultAction()), in which case ClickCount is ignored. If WhichButton is specified (for example "left", "right") then the native mouse Click function will be used to click the center of the element.
Click(WhichButton="", ClickCount=1, DownOrUp="", Relative="") {
;StringLower, WhichButton, WhichButton
if (WhichButton == "") {
if (this.GetCurrentPropertyValue(UIA_Enum.UIA_IsInvokePatternAvailablePropertyId)) {
this.GetCurrentPatternAs("Invoke").Invoke()
return 1
}
if (this.GetCurrentPropertyValue(UIA_Enum.UIA_IsTogglePatternAvailablePropertyId)) {
togglePattern := this.GetCurrentPatternAs("Toggle"), toggleState := togglePattern.CurrentToggleState
togglePattern.Toggle()
if (togglePattern.CurrentToggleState != toggleState)
return 1
}
if (this.GetCurrentPropertyValue(UIA_Enum.UIA_IsExpandCollapsePatternAvailablePropertyId)) {
if ((expandState := (pattern := this.GetCurrentPatternAs("ExpandCollapse")).CurrentExpandCollapseState) == 0)
pattern.Expand()
Else
pattern.Collapse()
if (pattern.CurrentExpandCollapseState != expandState)
return 1
}
if (this.GetCurrentPropertyValue(UIA_Enum.UIA_IsSelectionItemPatternAvailablePropertyId)) {
selectionPattern := this.GetCurrentPatternAs("SelectionItem"), selectionState := selectionPattern.CurrentIsSelected
selectionPattern.Select()
if (selectionPattern.CurrentIsSelected != selectionState)
return 1
}
if (this.GetCurrentPropertyValue(UIA_Enum.UIA_IsLegacyIAccessiblePatternAvailablePropertyId)) {
this.GetCurrentPatternAs("LegacyIAccessible").DoDefaultAction()
return 1
}
return 0
} else {
if !(pos := this.GetClickablePoint()).x {
pos := this.GetCurrentPos() ; or should only GetClickablePoint be used instead?
Click, % pos.x+pos.w//2 " " pos.y+pos.h//2 " " WhichButton (ClickCount ? " " ClickCount : "") (DownOrUp ? " " DownOrUp : "") (Relative ? " " Relative : "")
} else
Click, % pos.x " " pos.y " " WhichButton (ClickCount ? " " ClickCount : "") (DownOrUp ? " " DownOrUp : "") (Relative ? " " Relative : "")
}
}
; ControlClicks the element after getting relative coordinates with GetClickablePointRelativeTo("window"). Specifying WinTitle makes the function faster, since it bypasses getting the Hwnd from the element.
ControlClick(WinTitle="", WinText="", WhichButton="", ClickCount="", Options="", ExcludeTitle="", ExcludeText="") {
if (WinTitle == "")
WinTitle := "ahk_id " this.GetParentHwnd()
if !(pos := this.GetClickablePointRelativeTo("window")).x {
pos := this.GetCurrentPos("window") ; or should GetClickablePoint be used instead?
ControlClick, % "X" pos.x+pos.w//2 " Y" pos.y+pos.h//2, % WinTitle, % WinText, % WhichButton, % ClickCount, % Options, % ExcludeTitle, % ExcludeText
} else
ControlClick, % "X" pos.x " Y" pos.y, % WinTitle, % WinText, % WhichButton, % ClickCount, % Options, % ExcludeTitle, % ExcludeText
}
; Returns an object containing the x, y coordinates and width and height: {x:x coordinate, y:y coordinate, w:width, h:height}. relativeTo can be client, window or screen, default is A_CoordModeMouse.
GetCurrentPos(relativeTo="") {
relativeTo := (relativeTo == "") ? A_CoordModeMouse : relativeTo
StringLower, relativeTo, relativeTo
br := this.CurrentBoundingRectangle
if (relativeTo == "screen")
return {x:br.l, y:br.t, w:(br.r-br.l), h:(br.b-br.t)}
else {
hwnd := this.GetParentHwnd()
;WinGetTitle, wTitle, ahk_id %hwnd% ; for debugging purposes
;ToolTip, %wTitle%
if ((relativeTo == "window") || (relativeTo == "relative")) {
VarSetCapacity(RECT, 16)
DllCall("user32\GetWindowRect", "Ptr", hwnd, "Ptr", &RECT)
return {x:(br.l-NumGet(&RECT, 0, "Int")), y:(br.t-NumGet(&RECT, 4, "Int")), w:(br.r-br.l), h:(br.b-br.t)}
} else if (relativeTo == "client") {
VarSetCapacity(pt,8,0), NumPut(br.l,&pt,0,"int"), NumPut(br.t,&pt,4,"int")
DllCall("ScreenToClient", "Ptr",hwnd, "Ptr",&pt)
return {x:NumGet(pt,"int"), y:NumGet(pt,4,"int"), w:(br.r-br.l), h:(br.b-br.t)}
}
}
}
; By default get only direct children (UIA_TreeScope_Children := 0x2)
GetChildren(scope=0x2) {
return this.FindAll(this.TrueCondition, scope)
}
; Get all child elements using TreeViewer
TWGetChildren() {
arr := []
if !IsObject(nextChild := this.TreeWalkerTrue.GetFirstChildElement(this))
return 0
arr.Push(nextChild)
while IsObject(nextChild := this.TreeWalkerTrue.GetNextSiblingElement(nextChild))
arr.Push(nextChild)
return arr
}
TWRecursive(maxDepth=20, layer="", useTreeWalker := False) { ; This function might hang if the element has thousands of empty custom elements (e.g. complex webpage)
StrReplace(layer, ".",, dotcount)
if (dotcount > maxDepth)
return ""
if !(children := (useTreeWalker ? this.TWGetChildren() : this.GetChildren()))
return ""
returnStr := ""
for k, v in children {
returnStr .= layer . (layer == "" ? "" : ".") . k " " v.Dump() . "`n" . v.TWRecursive(maxDepth, layer (layer == "" ? "" : ".") k)
}
return returnStr
}
; Returns info about the element: ControlType, Name, Value, LocalizedControlType, AutomationId, AcceleratorKey.
Dump() {
return "Type: " this.CurrentControlType ((name := this.CurrentName) ? " Name: """ name """" : "") ((val := this.CurrentValue) ? " Value: """ val """": "") ((lct := this.CurrentLocalizedControlType) ? " LocalizedControlType: """ lct """" : "") ((aid := this.CurrentAutomationId) ? " AutomationId: """ aid """": "") ((ak := this.CurrentAcceleratorKey) ? " AcceleratorKey: """ ak """": "")
}
; Returns info (ControlType, Name etc) for all descendants of the element. maxDepth is the allowed depth of recursion, by default 20 layers. DO NOT call this on the root element!
DumpAll(maxDepth=20) {
return (this.Dump() . "`n" . this.TWRecursive(maxDepth))
}
/*
FindFirst using search criteria.
expr:
Takes a value in the form of "PropertyId=matchvalue" to match a specific property with the value matchValue. PropertyId can be most properties from UIA_Enum.UIA_PropertyId method (for example Name, ControlType, AutomationId etc).
Example1: "Name=Username:" would use FindFirst with UIA_Enum.UIA_NamePropertyId matching the name "Username:"
Example2: "ControlType=Button would FindFirst using UIA_Enum.UIA_ControlTypePropertyId and matching for UIA_Enum.UIA_ButtonControlTypeId. Alternatively "ControlType=50000" can be used (direct value for UIA_ButtonControlTypeId which is 50000)
Criteria can be combined with AND, OR, &&, ||:
Example3: "Name=Username: AND ControlType=Button" would FindFirst an element with the name property of "Username:" and control type of button.
Parenthesis are not supported! Criteria are evaluated left to right, so "a AND b OR c" would be evaluated as "(a and b) or c".
Negation can be specified with NOT:
Example4: "NOT ControlType=Edit" would return the first element that is not an edit element
scope:
Scope by default is UIA_TreeScope_Descendants.
matchMode:
If using Name PropertyId as a criteria, this follows the SetTitleMatchMode scheme:
1=name must must start with the specified name
2=can contain anywhere
3=exact match
RegEx=using regular expression. In this case the Name can't be empty.
caseSensitive:
If matching for a string, this will specify case-sensitivity.
*/
FindFirstBy(expr, scope=0x4, matchMode=3, caseSensitive=True) {
pos := 1, match := "", createCondition := "", operator := "", bufName := []
while (pos := RegexMatch(expr, "(.*?)=(.*?)( AND | OR | && | \|\| |$)", match, pos+StrLen(match))) {
if !match
break
if (InStr(match1, "Name") && (matchMode != 2) && (matchMode != 3)) {
bufName[1] := match1, bufName[2] := match2
Continue
} else {
;MsgBox, % "Creating condition with: m1: """ match1 """ m2: """ match2 """ m3: """ match3 """ flags: " ((matchMode==2)?2:0)|!caseSensitive
newCondition := (SubStr(match1, 1, 4) == "NOT ") ? this.__UIA.CreateNotCondition(this.__UIA.CreateCondition(SubStr(match1, 5), match2, ((matchMode==2 && match1=="Name")?2:0)|!caseSensitive)) : this.__UIA.CreateCondition(match1, match2, ((matchMode==2 && match1=="Name")?2:0)|!caseSensitive)
}
fullCondition := (operator == " AND " || operator == " && ") ? this.__UIA.CreateAndCondition(fullCondition, newCondition) : (operator == " OR " || operator == " || ") ? this.__UIA.CreateOrCondition(fullCondition, newCondition) : newCondition
operator := match3
}
if (bufName[1]) {
notProp := !InStr(bufName[1], "NOT "), name := bufName[2]
nameCondition := (matchMode==1)?this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name,, 2|!caseSensitive):this.__UIA.CreateNotCondition(this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_NamePropertyId, ""))
fullCondition := IsObject(fullCondition) ? this.__UIA.CreateAndCondition(nameCondition, fullCondition) : nameCondition
for k, v in this.FindAll(fullCondition, scope) {
curName := v.CurrentName
if notProp {
if (((matchMode == 1) && (SubStr(curName, 1, StrLen(name)) = name)) || (InStr(matchMode, "RegEx") && RegExMatch(curName, name)))
return v
} else {
if (((matchMode == 1) && !(SubStr(curName, 1, StrLen(name)) = name)) || (InStr(matchMode, "RegEx") && !RegExMatch(curName, name)))
return v
}
}
} else {
return this.FindFirst(fullCondition, scope)
}
}
; FindFirst using UIA_NamePropertyId. "scope" is search scope, which can be any of UIA_Enum TreeScope values. "MatchMode" has same convention as window TitleMatchMode: 1=needs to start with the specified name, 2=can contain anywhere, 3=exact match, RegEx=regex match.
FindFirstByName(name, scope=0x4, matchMode=3, caseSensitive=True) {
if (matchMode == 3 || matchMode == 2) {
nameCondition := this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name,, ((matchMode==3)?0:2)|!caseSensitive)
return this.FindFirst(nameCondition, scope)
}
nameCondition := (matchMode==1)?this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name,, 2|!caseSensitive):this.__UIA.CreateNotCondition(this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_NamePropertyId, ""))
for k, v in this.FindAll(nameCondition, scope) {
curName := v.CurrentName
if (((matchMode == 1) && (SubStr(curName, 1, StrLen(name)) = name)) || ((matchMode == "RegEx") && RegExMatch(curName, name)))
return v
}
}
; FindFirst using UIA_ControlTypeId. controlType can be the ControlTypeId numeric value, or in string form (eg "Button")
FindFirstByType(controlType, scope=0x4) {
if controlType is not integer
controlType := UIA_Enum.UIA_ControlTypeId(controlType)
if !controlType
throw Exception("Invalid control type specified", -1)
controlCondition := this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_ControlTypePropertyId, controlType)
return this.FindFirst(controlCondition, scope)
}
; FindFirst using UIA_NamePropertyId and UIA_ControlTypeId. controlType can be the ControlTypeId numeric value, or in string form (eg "Button"). scope is search scope, which can be any of UIA_Enum TreeScope values. matchMode has same convention as window TitleMatchMode: 1=needs to start with the specified name, 2=can contain anywhere, 3=exact match, RegEx=regex match
FindFirstByNameAndType(name, controlType, scope=0x4, matchMode=3, caseSensitive=True) {
if controlType is not integer
controlType := UIA_Enum.UIA_ControlTypeId(controlType)
if !controlType
throw Exception("Invalid control type specified", -1)
controlCondition := this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_ControlTypePropertyId, controlType, 3)
if (matchMode == 3 || matchMode == 2) {
nameCondition := this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name,, ((matchMode==3)?0:2)|!caseSensitive)
AndCondition := this.__UIA.CreateAndCondition(nameCondition, controlCondition)
return this.FindFirst(AndCondition, scope)
}
nameCondition := (matchMode==1)?this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name,, 2|(!caseSensitive)):this.__UIA.CreateNotCondition(this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_NamePropertyId, ""))
AndCondition := this.__UIA.CreateAndCondition(nameCondition, controlCondition)
for k, v in this.FindAll(AndCondition, scope) {
curName := v.CurrentName
if (((matchMode == 1) && InStr(SubStr(curName, 1, StrLen(name)), name)) || ((matchMode == "RegEx") && RegExMatch(curName, name)))
return v
}
}
; FindAll using an expression containing the desired conditions. For more information about expr, see FindFirstBy explanation
FindAllBy(expr, scope=0x4, matchMode=3, caseSensitive=True) {
pos := 1, match := "", createCondition := "", operator := "", bufName := []
while (pos := RegexMatch(expr, "(.*?)=(.*?)( AND | OR | && | \|\| |$)", match, pos+StrLen(match))) {
if !match
break
if (InStr(match1, "Name") && (matchMode != 2) && (matchMode != 3)) {
bufName[1] := match1, bufName[2] := match2
Continue
} else {
newCondition := (SubStr(match1, 1, 4) == "NOT ") ? this.__UIA.CreateNotCondition(this.__UIA.CreateCondition(SubStr(match1, 5), match2)) : this.__UIA.CreateCondition(match1, match2, ((matchMode==2 && match1=="Name")?2:0)|!caseSensitive)
}
fullCondition := (operator == " AND " || operator == " && ") ? this.__UIA.CreateAndCondition(fullCondition, newCondition) : (operator == " OR " || operator == " || ") ? this.__UIA.CreateOrCondition(fullCondition, newCondition) : newCondition
operator := match3
}
if (bufName[1]) {
notProp := !InStr(bufName[1], "NOT "), name := bufName[2], returnArr := []
nameCondition := (matchMode==1)?this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name,, 2|!caseSensitive):this.__UIA.CreateNotCondition(this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_NamePropertyId, ""))
fullCondition := IsObject(fullCondition) ? this.__UIA.CreateAndCondition(nameCondition, fullCondition) : nameCondition
for k, v in this.FindAll(fullCondition, scope) {
curName := v.CurrentName
if notProp {
if (((matchMode == 1) && (SubStr(curName, 1, StrLen(name)) = name)) || ((matchMode == "RegEx") && RegExMatch(curName, name)))
returnArr.Push(v)
} else {
if (((matchMode == 1) && !(SubStr(curName, 1, StrLen(name)) = name)) || ((matchMode == "RegEx") && !RegExMatch(curName, name)))
returnArr.Push(v)
}
}
return returnArr
} else {
return this.FindAll(fullCondition, scope)
}
}
; FindAll using UIA_NamePropertyId. scope is search scope, which can be any of UIA_Enum TreeScope values. matchMode has same convention as window TitleMatchMode: 1=needs to start with the specified name, 2=can contain anywhere, 3=exact match, RegEx=regex match
FindAllByName(name, scope=0x4, matchMode=3, caseSensitive=True) {
if (matchMode == 3 || matchMode == 2) {
nameCondition := this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name,, ((matchMode==3)?0:2)|!caseSensitive)
return this.FindAll(nameCondition, scope)
}
nameCondition := (matchMode==1)?this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name,, 2|!caseSensitive):this.__UIA.CreateNotCondition(this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_NamePropertyId, ""))
retList := []
for k, v in this.FindAll(nameCondition, scope) {
curName := v.CurrentName
if (((matchMode == 1) && (SubStr(curName, 1, StrLen(name)) = name)) || ((matchMode == "RegEx") && RegExMatch(curName, name)))
retList.Push(v)
}
return retList
}
; FindAll using UIA_ControlTypeId. controlType can be the ControlTypeId numeric value, or in string form (eg "Button"). scope is search scope, which can be any of UIA_Enum TreeScope values.
FindAllByType(controlType, scope=0x4) {
if controlType is not integer
controlType := UIA_Enum.UIA_ControlTypeId(controlType)
if !controlType
throw Exception("Invalid control type specified", -1)
controlCondition := this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_ControlTypePropertyId, controlType)
return this.FindAll(controlCondition, scope)
}
; FindAll using UIA_NamePropertyId and UIA_ControlTypeId. controlType can be the ControlTypeId numeric value, or in string form (eg "Button"). scope is search scope, which can be any of UIA_Enum TreeScope values. matchMode has same convention as window TitleMatchMode: 1=needs to start with the specified name, 2=can contain anywhere, 3=exact match, RegEx=regex match
FindAllByNameAndType(name, controlType, scope=0x4, matchMode=3) {
if controlType is not integer
controlType := UIA_Enum.UIA_ControlTypeId(controlType)
if !controlType
throw Exception("Invalid control type specified", -1)
controlCondition := this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_ControlTypePropertyId, controlType)
if (matchMode == 3 || matchMode == 2) {
nameCondition := this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name, ((matchMode==3)?0:2)|!caseSensitive)
AndCondition := this.__UIA.CreateAndCondition(nameCondition, controlCondition)
return this.FindAll(AndCondition, scope)
}
nameCondition := (matchMode==1)?this.__UIA.CreatePropertyConditionEx(UIA_Enum.UIA_NamePropertyId, name, , 2|!caseSensitive):this.__UIA.CreateNotCondition(this.__UIA.CreatePropertyCondition(UIA_Enum.UIA_NamePropertyId, ""))
AndCondition := this.__UIA.CreateAndCondition(nameCondition, controlCondition)
returnArr := []
for k, v in this.FindAll(AndCondition, scope) {
curName := v.CurrentName
if (((matchMode == 1) && (SubStr(curName, 1, StrLen(name)) = name)) || ((matchMode == "RegEx") && RegExMatch(curName, name)))
returnArr.Push(v)
}
return returnArr
}
; Gets an element by the "path" that is displayed in the UIA_Element.DumpAll() result. This is like the Acc path, but for UIA (they are not compatible).
FindByPath(searchPath="") {
el := this
Loop, Parse, searchPath, .
{
children := el.GetChildren()
if !IsObject(el := children[A_LoopField])
return
}
return el
}
; Calls UIA_Element.FindFirstBy until the element is found and then returns it, with a timeOut of 10000ms (10 seconds). For explanations of the other arguments, see FindFirstBy
WaitElementExist(expr, scope=0x4, matchMode=3, caseSensitive=True, timeOut=10000) {
startTime := A_TickCount
while (!IsObject(el := this.FindFirstBy(expr, scope, matchMode, caseSensitive)) && ((timeOut < 1) ? 1 : (A_tickCount - startTime < timeOut)))
Sleep, 100
return el
}
; Tries to FindFirstBy the element and if it is found then waits until the element doesn't exist (using WaitNotExist()), with a timeOut of 10000ms (10 seconds). For explanations of the other arguments, see FindFirstBy
WaitElementNotExist(expr, scope=0x4, matchMode=3, caseSensitive=True, timeOut=10000) {
return !IsObject(el := this.FindFirstBy(expr, scope, matchMode, caseSensitive)) || el.WaitNotExist(timeOut)
}
; Calls UIA_Element.FindFirstByName until the element is found and then returns it, with a timeOut of 10000ms (10 seconds)
WaitElementExistByName(name, scope=0x4, matchMode=3, caseSensitive=True, timeOut=10000) {
startTime := A_TickCount
while (!IsObject(el := this.FindFirstByName(name, scope, matchMode, caseSensitive)) && ((timeOut < 1) ? 1 : (A_tickCount - startTime < timeOut)))
Sleep, 100
return el
}
; Calls UIA_Element.FindFirstByType until the element is found and then returns it, with a timeOut of 10000ms (10 seconds)