-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws4ahk.ahk
2840 lines (2575 loc) · 86.2 KB
/
ws4ahk.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
/****h* /ws4ahk
* About
* Windows Scripting for Autohotkey (stdlib) v0.21 beta
*
* Requires Autohotkey v1.0.47 or above.
*
* Home page: http://www.autohotkey.net/~easycom/
*
* This module contains functions to embed VBScript or JScript into your AHK
* program, and as such, provides simple access to COM though these languages.
* This module also provides functions to create COM controls which can be
* controlled via VBScript or JScript.
*
* You might also look at this module as a means to add GUI abilities to
* VBScript/JScript. These Microsoft Scripting languages do not natively
* provide a way to show Windows, or even call DLL functions. By combining
* these Microsoft Scripting languages with Autohotkey, you get the best of both
* worlds.
*
* Note that this module requires use of the "Microsoft Scripting Control"
* which is usually installed on most machines. In the rare case it is not
* installed on a system, it may be downloaded from Microsoft and installed.
*
* http://www.microsoft.com/downloads/details.aspx?FamilyId=D7E31492-2595-49E6-8C02-1426FEC693AC
*
* As an alternative, the Microsoft Scripting Control file "msscript.ocx" may
* be used directly (e.g. placed in the same folder as the AHK script), so
* there is no need to actually install it (see WS_Initialize for how).
*
* Links
* List of Automation errors
* http://support.microsoft.com/kb/186063
*
* VBScript Language Reference
* http://msdn2.microsoft.com/en-us/library/d1wf56tt.aspx
*
* JScript Language Reference
* http://msdn2.microsoft.com/en-us/library/yek4tbz0.aspx
*
* The MSDN guru on WSH
* http://blogs.msdn.com/ericlippert/archive/2004/07/14/183241.aspx
*
* MSDN article "Adding Scripting Support to Your Application" goes over the
* functions of the Microsoft Scripting Control.
* http://msdn.microsoft.com/en-us/library/aa227413(VS.60).aspx
*
* To Do
* * Figure out Locale ID handling (e.g. try using English VB in German locale)
* * Create test suite
* * Make internal variable naming conventions more consistent
* * 3 error types (HRESULT, DllCall, other function): formalize the error
* format for easier parsing
*
* License
* Copyright (c) 2007,2008 Michael Sabin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******
*/
; ..............................................................................
/****** ws4ahk/WS_Initialize
* Description
* Initializes the Windows Scripting environment.
* Usage
* WS_Initialize( [ sLanguage = "VBScript" [, sMSScriptOCX ] ] )
* Parameters
* * sLanguage -- (Optional) (String) Either "VBScript" or "JScript".
* * sMSScriptOCX -- (Optional) (String) Path to msscript.ocx file.
* Return Value
* (Boolean) True on success, False on failure.
* ErrorLevel
* * Success: 0, or non-critical error description.
* * Failure: error description.
* Remarks
* This function must be called before any other functions may be used.
*
* Normally the scripting environment is setup using the installed
* msscript.ocx file on the system. Alternatively, you may specify the path
* directly to a msscript.ocx file, even if it is not registered with the
* system (useful if the user does not have Microsoft Scripting Control
* installed).
*
* Repeated calls to this function are ignored.
* Related
* WS_Uninitialize
* Example
WS_Initialize()
; do stuff
WS_Uninitialize()
WS_Initialize("VBScript", "C:\Windows\system32\msscript.ocx")
; do stuff
WS_Uninitialize()
******
*/
WS_Initialize(sLanguage = "VBScript", sMSScriptOCX="")
{
global __WS_iScriptControlObj__, __WS_iScriptErrorObj__
static ProgId_ScriptControl := "MSScriptControl.ScriptControl"
static CLSID_ScriptControl := "{0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC}"
static IID_ScriptControl := "{0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}"
IfNotEqual, __WS_iScriptControlObj__,
Return True ; Windows Scripting has already been initialized
; Init COM
iErr := DllCall("ole32\CoInitialize", "UInt", 0, "Int")
If (__WS_IsComError("CoInitialize", iErr))
Return False
; Create Scripting Control
If (sMSScriptOCX="")
__WS_iScriptControlObj__ := WS_CreateObject(ProgId_ScriptControl, IID_ScriptControl)
Else
__WS_iScriptControlObj__ := WS_CreateObjectFromDll(sMSScriptOCX, CLSID_ScriptControl, IID_ScriptControl)
IfEqual, __WS_iScriptControlObj__,
{
WS_Uninitialize()
Return False
}
; Set the language
If (!__WS_IScriptControl_Language(__WS_iScriptControlObj__, sLanguage))
{ ; Failed to set language
WS_Uninitialize()
Return False
}
; Get Error object
__WS_iScriptErrorObj__ := __WS_IScriptControl_Error(__WS_iScriptControlObj__)
IfEqual, __WS_iScriptErrorObj__,
{ ; Failed to get error object
WS_Uninitialize()
Return False
}
Return True
}
; ..............................................................................
/****** ws4ahk/WS_Uninitialize
* Description
* Uninitializes the Windows Scripting environment
* and releases the allocated resources.
* Usage
* WS_Uninitialize()
* Return Value
* None ("").
* ErrorLevel
* If an error occured while trying to release allocated resources, ErrorLevel
* will be set to an error description. If no error occured, ErrorLevel is
* unchanged.
* Remarks
* Call this function to free the memory used by this library. It is not
* necessary to call this function before exiting your script (but it is
* good practice).
*
* This function may be called repeatedly.
* Related
* WS_Initialize
* Example
; see WS_Initialize example
******
*/
WS_Uninitialize()
{
global __WS_iScriptControlObj__, __WS_iScriptErrorObj__
If __WS_iScriptErrorObj__ is Integer
If (__WS_iScriptErrorObj__ <> 0)
__WS_IUnknown_Release(__WS_iScriptErrorObj__)
If __WS_iScriptControlObj__ is Integer
If (__WS_iScriptControlObj__ <> 0)
__WS_IUnknown_Release(__WS_iScriptControlObj__)
ErrLvl := ErrorLevel ; save ErrorLevel
DllCall("ole32\CoUninitialize")
ErrorLevel := ErrLvl ; restore ErrorLevel
__WS_iScriptControlObj__ := ""
__WS_iScriptErrorObj__ := ""
}
; ..............................................................................
/****** ws4ahk/WS_Exec
* Description
* Executes scripting code.
* Usage
* WS_Exec(sScriptCode)
* Parameters
* * sScriptCode - (String) Scripting code to execute.
* Return Value
* (Boolean) True on success, False on failure.
* ErrorLevel
* * Success: 0, or non-critical error description.
* * Failure: error description.
* Remarks
* If WS_Initialize() has not been called, an error message will be displayed
* and the program will exit.
*
* By default, the Microsoft Scripting Control only allows scripts to run for
* 5 seconds before considering it 'hung', and the script is stopped
* (this can be changed, but hasn't been implemented in this library).
* Related
* WS_Eval, VBStr, JStr
* Example
#Include ws4ahk.ahk
WS_Initialize()
; Using a block of code like this makes it easy to
; add functions to the scripting environment.
; But always be sure to escape any percent signs (%)
Code =
(
foo = "bar"
Sub MsgFoo()
Msgbox foo
End Sub
)
WS_Exec(Code)
WS_Exec("MsgFoo")
******
*/
WS_Exec(sCode)
{
global __WS_iScriptControlObj__, __WS_iScriptErrorObj__
IfEqual __WS_iScriptControlObj__,
{
Msgbox % "Windows Scripting has not been initialized!`nExiting application."
ExitApp
}
; Run the code
Critical, On ; For thread safty
iErr := __WS_IScriptControl_ExecuteStatement(__WS_iScriptControlObj__, sCode)
If (iErr = "")
{
Critical, Off
; ErrorLevel has already been set to whatever error occured
Return False
}
Else
{
ErrLvl := ErrorLevel ; save ErrorLevel
blnIsErr := __WS_IsComError("IScriptControl::ExecuteStatement", iErr)
If (ErrorLevel = 0)
ErrorLevel := ErrLvl ; restore ErrorLevel
Else
ErrorLevel := ErrLvl "`n" ErrorLevel ; append ErrorLevel
If (blnIsErr)
{
; Probably an exception. Get the deatils.
; TODO: Find out what HRESULT code(s) mean there is an exception.
; FIXME: This call destroys whatever ErrorLevel is
__WS_HandleScriptError()
Critical, Off
Return False
}
Else ; success
{
Critical, Off
Return True
}
}
}
; ..............................................................................
/****** ws4ahk/WS_Eval
* Description
* Evaluates scripting code and returns the result.
* Usage
* WS_Eval(ByRef ReturnValue, sScriptCode)
* Parameters
* * ReturnValue -- (ByRef) Variable to receive the return value.
* * sScriptCode -- (String) Scripting code to evaluate.
* Return Value
* (Boolean) True on success, False on failure.
* ErrorLevel
* * Success: 0, or non-critical error description.
* * Failure: error description.
* Remarks
* ReturnValue will hold the result of an evaluation. Most return types are
* handled. Unhandled types are: Array, Currency, Date, VARIANT*, and the
* mysterious DECIMAL* type. You must convert these unhandled types to another
* type (usually string) before they can be returned.
*
* If an expression results in an unhandled type, the function will return
* True (because the expression was evaluated), but ReturnValue will be set
* to "#Unhandled return type#".
*
* Note also that if the expression returns an object, the object should be
* released via the WS_ReleaseObject() function when it is no longer needed.
*
* If WS_Initialize() has not been called, an error message will be displayed
* and the program will exit.
*
* By default, the Microsoft Scripting Control only allows scripts to run for
* 5 seconds before considering it 'hung', and the script is stopped
* (this can be changed, but hasn't been implemented in this library).
* Related
* WS_Exec, VBStr, JStr
* Example
#Include ws4ahk.ahk
WS_Initialize()
Code =
(
Function Square(x)
Square = x * x
End Function
)
WS_Exec(Code)
WS_Eval(Ret, "Square(6)")
Msgbox % Ret
******
*/
WS_Eval(ByRef xReturn, sCode)
{
global __WS_iScriptControlObj__, __WS_iScriptErrorObj__
IfEqual __WS_iScriptControlObj__,
{
Msgbox % "Windows Scripting has not been initialized!`nExiting application."
ExitApp
}
; Run the code
Critical, On ; For thread safty
iErr := __WS_IScriptControl_Eval(__WS_iScriptControlObj__, sCode, varReturn)
If (iErr = "")
{
Critical, Off
; ErrorLevel has already been set to whatever error occured
Return False
}
Else
{
ErrLvl := ErrorLevel ; save ErrorLevel
blnIsErr := __WS_IsComError("IScriptControl::Eval", iErr)
If (ErrorLevel = 0)
ErrorLevel := ErrLvl ; restore ErrorLevel
Else
ErrorLevel := ErrLvl "`n" ErrorLevel ; append ErrorLevel
If (blnIsErr)
{
; Probably an exception. Get the deatils.
; TODO: Find out what HRESULT code(s) mean there is an exception.
; FIXME: This call destroys whatever ErrorLevel is
__WS_HandleScriptError()
Critical, Off
Return False
}
Else ; success
{
If (!__WS_UnpackVARIANT(varReturn, xReturn))
xReturn := "#Unhandled return type#"
Critical, Off
Return True
}
}
}
; ..............................................................................
/****ix* Internal Functions/__WS_HandleScriptError
* Description
* Sets ErrorLevel with the last ScriptError.Description.
* Usage
* __WS_HandleScriptError()
* Return Value
* None ("").
* ErrorLevel
* The ScriptError.Description text, or if there is no text, a default
* automation error message with number.
* Remarks
* Also clears the last script error.
* Related
* WS_Exec, WS_Eval
******
*/
__WS_HandleScriptError()
{
global __WS_iScriptErrorObj__
sErrorDesc := __WS_IScriptError_Description(__WS_iScriptErrorObj__)
IfEqual, sErrorDesc,
sErrorDesc := "Automation error " __WS_IScriptError_Number(__WS_iScriptErrorObj__)
__WS_IScriptError_Clear(__WS_iScriptErrorObj__)
ErrorLevel := sErrorDesc
}
; ..............................................................................
/****** ws4ahk/VBStr
* Description
* Wraps a string in quotes and escapes disallowed characters for use in VBScript.
* Usage
* VBStr(str)
* Parameters
* * str -- (String) String to escape.
* Return Value
* (String) Escaped string.
* ErrorLevel
* Not changed.
* Remarks
* Converts an Autohotkey string into a string usable in the scripting
* environment. Specifically, it escapes disallowed characters
* (e.g. quotes, carriage return) and, wraps the string in quotes.
* Related
* JStr, WS_Exec, WS_Eval
* Example
#Include ws4ahk.ahk
text := VBStr("this is ""a test""")
Msgbox % text
; This is equivalent to
; text := """this is """"a test"""""""
text =
(
Multi
Line
Text
)
text := VBStr(text)
Msgbox % text
; This is equivalent to
; text := """Multi"" & vbLf & ""Line"" & vbLf & ""Text"""
******
*/
VBStr(s)
{
StringReplace, s, s, ", "", All
StringReplace, s, s, `r, " & vbCr & ", All
StringReplace, s, s, `n, " & vbLf & ", All
StringReplace, s, s, `f, " & vbFormFeed & ", All
StringReplace, s, s, `b, " & vbBack & ", All
Return """" s """"
}
; ..............................................................................
/****** ws4ahk/JStr
* Description
* Wraps a string in quotes and escapes disallowed characters for use in JScript.
* Usage
* JStr(str)
* Parameters
* * str -- (String) String to escape.
* Return Value
* (String) Escaped string.
* ErrorLevel
* Not changed.
* Remarks
* Converts an Autohotkey string into a string usable in the scripting
* environment. Specifically, it escapes disallowed characters
* (e.g. quotes, carriage return) and, wraps the string in quotes.
* Related
* VBStr, WS_Exec, WS_Eval
* Example
#Include ws4ahk.ahk
text := JStr("this is ""a test""")
Msgbox % text
; This is equivalent to
; text := """this is \""a test\"""""
text =
(
Multi
Line
Text
)
text := JStr(text)
Msgbox % text
; This is equivalent to
; text := "\""Multi\nLine\nText\"""
******
*/
JStr(s)
{
StringReplace, s, s, \, \\, All
StringReplace, s, s, ", \", All
StringReplace, s, s, `r, \r, All
StringReplace, s, s, `n, \n, All
StringReplace, s, s, `f, \f, All
StringReplace, s, s, `b, \b, All
Return """" s """"
}
; ..............................................................................
/****** ws4ahk/WS_CreateObject
* Description
* Creates a new instance of a COM object.
* Usage
* WS_CreateObject(sProgIDorClassID [, sInterfaceID = IDispatch ] )
* Parameters
* * sProgIDorClassID -- (String) Program ID (e.g. "Excel.Application") or
* Class ID (e.g. "{0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC}").
* * sInterfaceID -- (Optional) (String) Interface ID of the object to create
* (e.g. "{0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}").
* Return Value
* * Success: (Integer) Pointer to the created object.
* * Failure: None ("").
* ErrorLevel
* * Success: 0, or non-critical error description.
* * Failure: error description.
* Remarks
* In most cases it is better and faster to use the scripting
* environment to create and manage objects (using VBScript's CreateObject()
* function, and JScript's ActiveXObject() function).
*
* WS_ReleaseObject() should be called when the object is no longer needed.
*
* Note that the sInterfaceID parameter is only used for more advanced COM
* operations. Normally it can be ignored.
* Related
* WS_ReleaseObject
* Example
; This is a contrived example. Normally it is better and faster to use
; VBScript's CreateObject() function (or JScript's ActiveXObject() function).
#Include ws4ahk.ahk
WS_Initialize()
pSpObj := WS_CreateObject("SAPI.SpVoice")
WS_AddObject(pSpObj, "oSpeak")
WS_ReleaseObject(pSpObj) ; scripting environment has object, we don't need it anymore
WS_Exec("oSpeak.Speak %s", "Hello world!")
******
*/
WS_CreateObject(sProgID_ClsId, sIId = "{00020400-0000-0000-C000-000000000046}")
{ ; ^ IDispatch
static IID_IDispatch := "{00020400-0000-0000-C000-000000000046}"
static CLSCTX_INPROC_SERVER := 1
static CLSCTX_INPROC_HANDLER := 2
static CLSCTX_LOCAL_SERVER := 4
static CLSCTX_INPROC_SERVER16 := 8
static CLSCTX_REMOTE_SERVER := 16
If (InStr(sProgID_ClsId, "{")) ; Is it a CLSID?
{
If (!__WS_CLSIDFromString(sProgID_ClsId, sbinClassId))
Return ; unable to create binary class id
}
Else
{
If (!__WS_CLSIDFromProgID(sProgID_ClsId, sbinClassId))
Return ; unable to create binary class id
}
If (!__WS_IIDFromString(sIId, sbinIId))
Return ; unable to create binary interface id
iErr := DllCall("ole32\CoCreateInstance"
, "Str" , sbinClassId
, "UInt" , 0
, "Int" , CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER
, "Str" , sbinIId
, "UInt*", ppv
, "Int")
If (__WS_IsComError("CoCreateInstance", iErr))
Return
If (sIId = IID_IDispatch)
Return __WS_GetIDispatch(ppv)
Else
Return ppv
}
; ..............................................................................
/****** ws4ahk/WS_GetObject
* Description
* Get the instance of an already existing COM object.
* Usage
* WS_GetObject(sProgIDorClassID [, sInterfaceID = IDispatch ] )
* Parameters
* * sProgIDorClassID -- (String) Program ID (e.g. "Excel.Application") or
* Class ID (e.g. "{0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC}").
* * sInterfaceID -- (Optional) (String) Interface ID
* (e.g. "{0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}").
* Return Value
* * Success: (Integer) Pointer to the existing instance of the object.
* * Failure: None ("").
* ErrorLevel
* * Success: 0, or non-critical error description.
* * Failure: error description.
* Remarks
* In most cases it is better and faster to use the
* GetObject() function in the scripting environment instead of this function.
*
* WS_ReleaseObject() should be called when the object is no longer needed.
*
* Note that the sInterfaceID parameter is only used for really advanced COM
* operations. Normally it can be ignored.
* Related
* WS_ReleaseObject
* Example
; This example works best if Microsoft Excel is installed.
; This is a contrived example. Normally it is better and faster to use
; the script's GetObject() function.
#Include ws4ahk.ahk
WS_Initialize()
pExcel := WS_GetObject("Excel.Application")
If (pExcel = "")
{
Msgbox % "Excel isn't running."
}
Else
{
WS_AddObject(pExcel, "oExcel")
WS_ReleaseObject(pExcel)
WS_Eval(iWrkBks, "oExcel.Workbooks.Count")
Msgbox % "You have " iWrkBks " workbook(s) open in Excel."
}
******
*/
WS_GetObject(sProgID_ClsId, sIId = "{00020400-0000-0000-C000-000000000046}")
{ ; ^ IDispatch
static IID_IDispatch := "{00020400-0000-0000-C000-000000000046}"
; Get the binary form of class ID
If (InStr(sProgID_ClsId, "{")) ; Is it a CLSID string?
{
If (!__WS_CLSIDFromString(sProgID_ClsId, sbinClassId))
Return ; unable to create binary class id
}
Else ; it's a Prog ID
{
If (!__WS_CLSIDFromProgID(sProgID_ClsId, sbinClassId))
Return ; unable to create binary class id
}
; Get the object
iErr := DllCall("oleaut32\GetActiveObject"
, "Str", sbinClassId
, "UInt", 0
, "UInt*", pIUnkn
, "Int")
; Failed?
If (__WS_IsComError("GetActiveObject", iErr))
Return
ppv := __WS_IUnknown_QueryInterface(pIUnkn, sIId)
__WS_IUnknown_Release(pIUnkn)
; Did QueryInterface fail?
IfEqual, ppv,
Return
If (sIId = IID_IDispatch)
Return __WS_GetIDispatch(ppv)
Else
Return ppv
}
; ..............................................................................
/****** ws4ahk/WS_ReleaseObject
* Description
* Frees a reference to an object.
* Usage
* WS_ReleaseObject(pObject)
* Parameters
* * pObject - (Integer) Pointer to the object to be released.
* Return Value
* * Success: (Integer) Number of remaining references to the object.
* * Failure: None ("").
* ErrorLevel
* * Success: 0.
* * Failure: error description.
* Remarks
* Should be called on object pointers that are no longer needed so the
* reference can be freed.
*
* Calling this function on an object that is already released will
* crash your program!
* Related
* WS_CreateObject
* Example
#Include ws4ahk.ahk
WS_Initialize()
; Create an object in the scripting environment and return it to AHK
WS_Eval(oObj, "CreateObject(%s)", "Wscript.Shell")
; ... do something with the object
WS_ReleaseObject(oObj)
******
*/
WS_ReleaseObject(iObjPtr)
{
If iObjPtr is Integer
{
If (iObjPtr <> 0)
{
Return __WS_IUnknown_Release(iObjPtr)
}
Else
{
ErrorLevel := "WS_ReleaseObject() called with null pointer argument"
Return
}
}
Else
{
ErrorLevel := "WS_ReleaseObject() called with non-numeric argument"
Return
}
}
; ..............................................................................
/****** ws4ahk/WS_AddObject
* Description
* Adds a COM object to the scripting environment.
* Usage
* WS_AddObject(pObject, sName [, blnGlobalMembers = False ] )
* Parameters
* * pObject -- (Integer) Pointer of object to add.
* * sName -- (String) The identifier that will be used in the
* scripting environment to refer to this object.
* * blnGlobalMembers -- (Optional) (Boolean) Setting GlobalMembers to True will
* make all the members of the object global in the script.
* Return Value
* (Boolean) True on success, False on failure.
* ErrorLevel
* * Success: 0, or non-critical error description.
* * Failure: error description.
* Remarks
* Adds an object created in AHK to the scripting environment. Setting
* blnGlobalMembers to True will make all the members of the object global in
* the script.
*
* This function is most useful after creating a COM control. The COM object
* can be added to the scripting environment, and then the object can be
* controlled via the script.
*
* If WS_Initialize() has not been called, an error message will be displayed
* and the program will exit.
* Related
* WS_ReleaseObject
* Example
; see WS_CreateObject example
******
*/
WS_AddObject(pObject, sName, blnGlobalMembers = False)
{
global __WS_iScriptControlObj__
static IID_IDispatch := "{00020400-0000-0000-C000-000000000046}"
IfEqual __WS_iScriptControlObj__,
{
Msgbox % "Windows Scripting has not been initialized!`nExiting application."
ExitApp
}
Return __WS_IScriptControl_AddObject(__WS_iScriptControlObj__, sName, pObject
, -blnGlobalMembers)
}
; ## COM Controls ##############################################################
; These functions originally written by our resident COM guru Sean in
; the Autohotkey forums. They have ben expanded, commented, and renamed
; for easier reading. They have also been adjusted to use the WS4AHK COM
; API functions, and error checking has been added.
; These functions were small enough I figured they may as well just be included.
; Windows Scripting does not have to be initialized before using these functions.
; ..............................................................................
/****** ws4ahk/WS_InitComControls
* Description
* Initializes COM controls.
* Usage
* WS_InitComControls()
* Return Value
* * Success: (Integer) nonzero.
* * Failure: 0.
* ErrorLevel
* Set to DllCall() result.
* Remarks
* Must be called before calling WS_CreateComControlContainer.
*
* WS_Initialize() does not need to be called before calling this function.
*
* There is no harm in calling this function more than once.
* Related
* WS_UninitComControls, WS_CreateComControlContainer
* Example
; see WS_CreateComControlContainer example
******
*/
WS_InitComControls()
{
; Check if atl dll has already been loaded.
If !DllCall("GetModuleHandle", "Str", "atl")
DllCall("LoadLibrary" , "Str", "atl")
; Initialize atl (it's ok to call this function more than once)
Return DllCall("atl\AtlAxWinInit")
}
; ..............................................................................
/****** ws4ahk/WS_UninitComControls
* Description
* Uninitializes COM controls.
* Usage
* WS_UninitComControls()
* Return Value
* None ("").
* ErrorLevel
* Set to DllCall() result.
* Remarks
* Unloads the atl library.
*
* WS_Initialize() or WS_Uninitialize() do not need to be called before calling
* this function.
*
* Note: MSDN warns about a race condition that could
* occur if two threads called this function at the same time.
*
* http://msdn2.microsoft.com/en-us/library/ms885630.aspx
* Related
* WS_InitComControls
* Example
; see WS_CreateComControlContainer example
******
*/
WS_UninitComControls()
{
If hModule := DllCall("GetModuleHandle", "Str", "atl")
DllCall("FreeLibrary", "UInt", hModule)
}
; ..............................................................................
/****** ws4ahk/WS_GetHWNDofComControl
* Description
* Retrieves the Window Handle (i.e. hWnd, or ahk_id) associated with a COM
* control object.
* Usage
* WS_GetHWNDofComControl(pObject)
* Parameters
* * pObject - (Integer) Pointer to a COM control object.
* Return Value
* * Success: (Integer) The hWnd (i.e. ahk_id) of the control that hosts the COM object.
* * COM related failure: None ("").
* * Window related failure: 0 (NULL).
* ErrorLevel
* * Success: 0
* * COM related failure: COM error description.
* * Window related failure: DllCall() result.
* Remarks
* WS_CreateComControlContainer will return the hWnd when it creates the COM
* control. As such, this function isn't really necessary unless the COM
* control is created some other way, or the hWnd is somehow unavailable in
* a scope.
*
* WS_Initialize() does not need to be called before calling this function.
* Related
* WS_GetComControlInHWND, WS_AttachComControlToHWND
* Example
******
*/
; TODO: Maybe combine the error returns to be just one?
; TODO: Add example
WS_GetHWNDofComControl(pComObject)
{
static IID_IOleWindow := "{00000114-0000-0000-C000-000000000046}"
pOleWin := __WS_IUnknown_QueryInterface(pComObject, IID_IOleWindow)
IfEqual pOleWin,
Return
; IOleWindow::GetWindow()
iErr := DllCall(__WS_VTable(pOleWin, 3), "UInt", pOleWin, "UInt*", hWnd)
If (__WS_IsComError("IOleWindow::GetWindow", iErr))
Return
; will append to ErrorLevel if needed
__WS_IUnknown_Release(pOleWin)
Return DllCall("GetParent", "UInt", hWnd)
}
; ..............................................................................
/****** ws4ahk/WS_GetComControlInHWND
* Description
* Retrieves the COM control object associated with a COM control.
* Usage
* WS_GetComControlInHWND(hWnd)
* Parameters
* * hWnd - (Integer) The handle (i.e. ahk_id) of a COM control.
* Return Value
* * Success: (Integer) A pointer to an IDispach interface of the COM object
* in the HWND (i.e. ahk_id).
* * Failure: None ("").
* ErrorLevel
* * Success: 0, or non-critical error description.
* * Failure: error description.
* Remarks
* WS_Initialize() does not need to be called before calling this function.
* Related
* WS_GetHWNDofComControl, WS_AttachComControlToHWND
* Example
; see WS_CreateComControlContainer example
******
*/
WS_GetComControlInHWND(hWnd)
{
static IID_IDispatch := "{00020400-0000-0000-C000-000000000046}"
iErr := DllCall("atl\AtlAxGetControl"
, "UInt", hWnd
, "UInt*", pUnknown
, "Int")
If (__WS_IsComError("AtlAxGetControl", iErr))
Return
pDispatch := __WS_IUnknown_QueryInterface(pUnknown, IID_IDispatch)
__WS_IUnknown_Release(pUnknown)
Return pDispatch
}
; ..............................................................................
/****** ws4ahk/WS_AttachComControlToHWND
* Description
* Attaches a COM control object to an existing COM control container.
* Usage
* WS_AttachComControlToHWND(pObject, hWnd)
* Parameters
* * pObject - (Integer) Pointer to a COM control object.
* * hWnd - (Integer) Handle to a control to attach the COM object to.
* Return Value
* (Boolean) True on success, False on failure.
* ErrorLevel
* * Success: 0, or non-critical error description.
* * Failure: error description.
* Remarks
* Attaches a COM control object to a COM control container created using
* WS_CreateComControlContainer() function.
*
* WS_Initialize() does not need to be called before calling this function.
* Related
* WS_GetComControlInHWND, WS_GetHWNDofComControl
* Example
; Creates a WYSIWYG html editor in just 20 lines (method 1)
#Include ws4ahk.ahk
WS_Initialize()
WS_InitComControls()
Gui, +LastFound
Gui, Show, w800 h600 Center, DhtmlEdit Test
hWnd := WinExist()
COMhWnd := WS_CreateComControlContainer(hWnd, 10, 10, 780, 580)
ppvDEdit := WS_CreateObject("DhtmlEdit.DhtmlEdit")
WS_AttachComControlToHWND(ppvDEdit, COMhWnd)
WS_AddObject(ppvDEdit, "DHtmlControl")
; the scripting environment has the object, so we don't need it anymore
WS_ReleaseObject(ppvDEdit)