-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAmHotkey.ahk
3400 lines (2739 loc) · 92.3 KB
/
AmHotkey.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
; AmHotkey is the Modularized Autohotkey framework, created by Jimm Chen since 2010,
; based on the fantastic Autohotkey script engine.
;
; Tested with Autohotkey v1.1.32.00
#InstallKeybdHook
; Switch #include base-dir to A_ScriptDir:
#Include %A_ScriptDir%
#Include *i custom_env.ahk ; optional
global NOERROR_0 := 0
global g_winmove_unit := 50 ; window move unit small
global g_winmove_scale := 5 ; window move 5x larger step if you tap LCtrl just before doing win move
global g_saved_xMouseScreen := 0
global g_saved_yMouseScreen := 0
global g_MouseNudgeUnit = 10
global g_MouseNudgeUnitAM = 10 ; AM: Application Match
global g_MouseNudgeTitleAM = "Non-existing title"
; Write ``global`` so that these vars can be referenced in later functions' body.
global g_AmMute := false
;;;;;;;;;;;;;;;;;;;;;;;;;; ^^^ user configurable globals end ^^^ ;;;;;;;;;;;;;;;;;;;;;;;;;;
global g_UntitledNotpad := "Untitled - Notepad"
;global gc_AutoexecLabelsFilename := ""
global gc_AutoexecLabelsFilepath := A_ScriptDir "\autoexec-labels.autogen.ahk"
; #Include the very file right now, which is required by exerun.
#Include *i %A_ScriptDir%\autoexec-labels.autogen.ahk
global Eme_Fn_idle = true ; no need to configure
global g_clipboard_cache
global g_pathop_last_numop = 14
RegRead, g_CmdCompletionChar, HKEY_CURRENT_USER, Software\Microsoft\Command Processor, CompletionChar
global g_winx, g_winy, g_winwidth=-1, g_winheight
; These four vars tells previous window position before a window-size change,
; so that user can undo the change(if inadvertently changed an undesired window)
; g_winwidth = -1 means "these values are invalid now".
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Cope with auto-exec section in sub-ahk. Thanks to:
; http://www.autohotkey.com/board/topic/9890-multiple-auto-execute-sections/ with IsLabel() fix
global gc_customize_ahk := "customize.ahk"
; Constant used in dev_MsgBoxYesNo() etc.
global msgboxoption_Ok := 0
global msgboxoption_OkCancel := 1
global msgboxoption_YesNo := 4
global msgboxoption_YesNoCancel := 3
global msgboxoption_IconStop := 16
global msgboxoption_IconQuestion := 32
global msgboxoption_IconExclamation := 48
global msgboxoption_IconInfo := 64
global msgboxoption_2nddefault := 256
global msgboxoption_3rddefault := 512
global msgboxoption_SystemModal := 0x1000
global msgboxoption_TaskModal := 0x2000
global msgboxoption_Topmost := 0x40000
global g_amstrMute := "AM: Mute clicking sound"
global g_DefineHotkeyLogfile := "DefineHotkeys.log"
global g_tmpMonitorsLayout := {}
global g_AmHotkeyFilepath := A_LineFile ; Record my real filepath at runtime.
global g_AmHotkeyDirpath := dev_SplitPath(g_AmHotkeyFilepath)
global g_isdbg_DefineHotkeyLegacy := g_isdbg_DefineHotkeyLegacy_default
global g_isdbg_DefineHotkeyFlex := g_isdbg_DefineHotkeyFlex_default
; -- User can override g_isdbg_DefineHotkeyFlex_default in custom_env.ahk .
;==========;==========;==========;==========;==========;==========;==========;==========;
; All global vars should be defined ABOVE this line, otherwise, they will be null.
;==========;==========;==========;==========;==========;==========;==========;==========;
AmHotkey_DoInit()
Amhotkey_ScanAndLoadAutoexecLabels()
return
;################################################################################################
;################################### Global-exec section ENDS ###################################
;################################################################################################
#Include %A_LineFile%\..\libs\debugwin.ahk ; debugwin should be included first!
;
#Include %A_LineFile%\..\libs\WinClipAPI.ahk
#Include %A_LineFile%\..\libs\WinClip.ahk
#include %A_LineFile%\..\libs\Amhk-common.ahk
#include %A_LineFile%\..\libs\Amhk-gui.ahk
#include %A_LineFile%\..\libs\ClipboardMonitor.ahk
class AmHotkey ; Store global vars here
{
static dbgid_HotkeyFlex := "HotkeyFlex"
static dbgid_HotkeyLegacy := "HotkeyLegacy"
static hwnd_just_hidden := ""
static do_cut := 0
static do_copy := 1
}
AmHotkey_DoInit()
{
AmDbg_SetDesc(AmHotkey.dbgid_HotkeyFlex, "Debug message for fxhk_DefineHotkey() functions.")
AmDbg_SetDesc(AmHotkey.dbgid_HotkeyLegacy, "Debug message for dev_DefineHotkey() legacy functions.")
dev_MenuAddSepLine("TRAY")
dev_MenuAddItem("TRAY", Format("== {} ==", ts14short()), "dev_nop") ; so to distinguish different AmHotkey instance.
dev_MenuAddItem("TRAY", "Show debug-message window", "Dbgwin_ShowGui")
dev_MenuAddItem("TRAY", "Configure debug-modules", "Amdbg_ShowGui")
}
; ########## Some debugging hotkeys first ##########
; 2010-03-13 Win+Alt+R to reload current script
#!r:: Reload
; Win+Alt+C : Check Window class
!#c:: dev_CheckActiveWindowInfo()
dev_CheckActiveWindowInfo()
{
tooltip
Awinid := dev_ActivateLastSeenWindow()
if(!Awinid)
{
dev_MsgBoxInfo( "No active window can be found. Use hotkey Win+Alt+C instead." )
}
dev_CheckWindowInfo(Awinid)
}
dev_ActivateLastSeenWindow()
{
; Usage scenario:
; When a Systray Autohotkey menu item wants to operate current active window,
; there may not be an active window(``Awinid := dev_GetActiveHwnd()`` reports Awinid==null),
; so we can use this function to bring up the last seen active window.
Awinid := dev_GetActiveHwnd() ; cache active window unique id
if(!Awinid)
{
SendInput !{TAB}
Loop, 10
{
Awinid := dev_GetActiveHwnd()
if(Awinid)
break
Sleep, 100
}
}
return Awinid
}
dev_CheckWindowInfo(hwnd)
{
WinGetClass, class, ahk_id %hwnd%
WinGetTitle, title, ahk_id %hwnd%
WinGetPos, x,y,w,h, ahk_id %hwnd%
WinGet, pid, PID, ahk_id %hwnd%
WinGet, exepath, ProcessPath, ahk_id %hwnd%
ControlGetFocus, focusNN, ahk_id %hwnd%
ControlGet, focus_hctrl, HWND, , %focusNN%, ahk_id %hwnd%
x_end_ := x + w
y_end_ := y + h
cliRel := dev_WinGetClientAreaPos(hwnd)
caLeft := cliRel.x
caTop := cliRel.y
caRight := cliRel.x_
caBottom := cliRel.y_
caWidth := cliRel.w
caHeight := cliRel.h
CoordMode, Mouse, Screen
MouseGetPos, mxScreen, myScreen
CoordMode, Mouse, Window
MouseGetPos, mxWindow, myWindow, tophwnd_undermouse, classnn
if(classnn)
{
; Get child's relative position(relative to parent window's top-left corner).
ControlGetPos, xr_child, yr_child, wr_child, hr_child, %classnn%, ahk_id %tophwnd_undermouse%
xrend_child_ := xr_child + wr_child
yrend_child_ := yr_child + hr_child
; Get child's absolute position(screen coordinate).
ControlGet, hctrl_undermouse, HWND, , %classnn%, ahk_id %tophwnd_undermouse%
WinGetPos, x_child, y_child, w_child, h_child, ahk_id %hctrl_undermouse%
xend_child_ := x_child + w_child
yend_child_ := y_child + h_child
isHCtrlUnicode := DllCall("IsWindowUnicode", "Ptr", hctrl_undermouse)
ynHCtrlUnicode := isHCtrlUnicode ? "yes" : "no"
info_child =
(
ClassNN under mouse is "%classnn%"
hwndCtrl under mouse is "%hctrl_undermouse%"
RelaPos: X ( %xr_child% ~ %xrend_child_% ), Y ( %yr_child% ~ %yrend_child_% ), size ( %wr_child% x %hr_child% )
AbsPos: X ( %x_child% ~ %xend_child_% ), Y ( %y_child% ~ %yend_child_% ), size ( %w_child% x %h_child% )
IsWindowUnicode? [%ynHCtrlUnicode%]
)
}
else
{
classnn := ""
info_child := "No child-window under mouse cursor."
}
info =
(
The Active window class is "%class%" (Hwnd=%hwnd%)
Title is "%title%"
Position : X ( %x% ~ %x_end_% ), Y ( %y% ~ %y_end_% ), size ( %w% x %h% )
Client area: rX ( %caLeft% ~ %caRight% ), rY ( %caTop% ~ %caBottom% ), size ( %caWidth% x %caHeight% )
Current focused classnn: %focusNN%
Current focused hctrl: ahk_id=%focus_hctrl%
Process ID: %pid%
Process path: %exepath%
Mouse position: In-window: (%mxWindow%,%myWindow%) `; In-screen: (%mxScreen%,%myScreen%)
%info_child%
Answer [Yes] to see more system info.
)
more := dev_MsgBoxYesNo(info, false)
if(more)
{
Dbg_DumpSysInfo(true)
Dbg_DumpChildWinsInfo(tophwnd_undermouse)
}
}
dbgline_onevar(varname, showfmt:="")
{
if(not showfmt)
str := Format("{} = {}`n", varname, %varname%)
else if(showfmt=="t/f")
str := Format("{} = {}`n", varname, %varname% ? "true" : "false")
else if(showfmt=="hex")
str := Format("{} = 0x{:08X}`n", varname, %varname%)
return str
}
Dbg_DumpSysInfo(force_fgwin:=false)
{
info := "System info:`n"
info .= dbgline_onevar("A_OSVersion")
info .= dbgline_onevar("A_Is64bitOS", "t/f")
info .= dbgline_onevar("A_PtrSize")
info .= dbgline_onevar("A_IsAdmin", "t/f")
info .= dbgline_onevar("A_AppData")
info .= dbgline_onevar("A_ScreenDPI")
info .= dbgline_onevar("A_AhkVersion")
info .= dbgline_onevar("A_AhkPath")
info .= dbgline_onevar("A_WorkingDir")
info .= dbgline_onevar("A_ScriptDir")
info .= dbgline_onevar("A_ScriptName")
info .= dbgline_onevar("A_ScriptFullPath")
info .= dbgline_onevar("A_FileEncoding")
info .= dbgline_onevar("A_ScriptHwnd", "hex")
info .= dbgline_onevar("A_IsUnicode", "t/f")
info .= dbgline_onevar("A_IsCompiled", "t/f")
Dbgwin_Output(info, force_fgwin)
}
SystrayMenu_Add_MuteClicking()
{
Menu, TRAY, add, %g_amstrMute%, dev_AmMute ; Creates a new menu item.
}
dev_AmMute()
{
g_AmMute := !g_AmMute
if(g_AmMute) {
Menu, TRAY, Check, %g_amstrMute%
}
else {
Menu, TRAY, UnCheck, %g_amstrMute%
}
}
GetFirstNoncommentLine(ahkfilepath)
{
Loop, read, %ahkfilepath%
{
if(Trim(A_LoopReadLine)=="")
continue ; this is a blank line
else if( A_LoopReadLine ~= "^\s*(?=;);+" ) ; \s space or tab
{
continue ; this is a comment line
}
else
return A_LoopReadLine
}
return ""
}
amhk_AddAutoExecAhk(arAutoexecLabels, ahkdir, filename)
{
static s_dictAutoexecExistingFname := {} ; for checking duplicate
static s_dictAutoexecExistingLabel := {} ; for checking duplicate
ahkfilepath := ahkdir . "\" . filename
; check and skip duplicate
if(s_dictAutoexecExistingFname.HasKey(ahkfilepath)) {
return
}
; Check whether the first non comment line is in pattern AUTOEXEC_xxx:
chkline := GetFirstNoncommentLine(ahkfilepath)
foundpos := RegExMatch(chkline, "^(AUTOEXEC_[a-zA-Z0-9_.]+)\:", subpat)
if( foundpos>0 )
{
autoexec_label := subpat1
if(s_dictAutoexecExistingLabel.HasKey(autoexec_label))
{
; [2023-04-20] As of Autohotkey 1.1.32, this code will not have a chance to execute,
; bcz AHK engine will detect "Duplicate label" error and refuse to load the whole AHK.
dev_MsgBoxError(Format("User AHK error detected! The same label '{}' is defined in two ahk files:`n`n"
. "{}`n"
. "{}`n"
, autoexec_label, s_dictAutoexecExistingLabel[autoexec_label], ahkfilepath))
}
filename := dev_StripPrefix(ahkfilepath, A_ScriptDir "\")
arAutoexecLabels.Insert( {"filename":filename , "label":autoexec_label} )
s_dictAutoexecExistingFname[ahkfilepath] := autoexec_label
s_dictAutoexecExistingLabel[autoexec_label] := ahkfilepath
; Dbgwin_Output(autoexec_label " => " ahkfilepath)
}
}
Amhotkey_ScanAndLoadAutoexecLabels()
{
; "Call" auto-exec sections collected(for those ahks with AUTOEXEC_xxx: label at start of file)
if(!A_IsCompiled)
{
arAutoexecLabels := []
amhk_ScanAhkFilesForAutoexecLabels(arAutoexecLabels)
amhk_CallAutoexecLabels(arAutoexecLabels)
}
else
{
; For Ahk2Exe-compiled AmHotkey.exe
if(not AutoexecForExe.labels)
{
dev_MsgBoxError("The file 'autoexec-labels.autogen.ahk' did NOT exist or had wrong content "
. "when compiling this AHK-exe. You have to re-compile this exe.")
ExitApp
}
dict_DoneLabels := {}
for i,label in AutoexecForExe.labels
{
if(!dict_DoneLabels.HasKey(label) && IsLabel(label))
{
dict_DoneLabels[label] := true
; Dbgwin_Output("AHK-exe found existing label: " label) ; debug
GoSub, %label%
}
}
}
}
amhk_ScanAhkFilesForAutoexecLabels(arAutoexecLabels)
{
; Scan all ahk files in the same folder as the master(startup) ahk file,
; and store all found AUTOEXEC_xxx label info into arAutoexecLabels[] .
Loop, Files, % g_AmHotkeyDirpath "\*.ahk", R
{
; Loop, %A_ScriptDir%\*.ahk ; this matches XXX.ahkx , XXX.ahky etc (AHK bug?)
; so I have to filter it once more.
if(InStr(A_LoopFileFullPath, ".no-ahk"))
{
; We deliberately skip those dir with ".no-ahk" suffix.
continue
}
if(amhk_IsAutoGlobalFilename(A_LoopFileName))
{
amhk_AddAutoExecAhk(arAutoexecLabels, A_LoopFileDir, A_LoopFileName)
}
}
; If user has his own startup Script(known via A_ScriptDir, instead of AmHotkey.ahk),
; we scan and load ahk modules there.
;
if(not dev_StrIsEqualI(A_ScriptDir, g_AmHotkeyDirpath))
{
Loop, Files, %A_ScriptDir%\*.ahk, R
{
if(amhk_IsAutoGlobalFilename(A_LoopFileName))
{
amhk_AddAutoExecAhk(arAutoexecLabels, A_LoopFileDir, A_LoopFileName)
}
}
}
amhk_AddAutoExecAhk(arAutoexecLabels, A_ScriptDir, gc_customize_ahk)
; -- Load this at the final stage, because it is intended to override some
; global vars defined by other modules.
; [2022-12-28] Ahk2Exe support code:
;
autogen_content_fmt =
(
class AutoexecForExe
{
static labels := [ "NullLabel_placeholder"
{}, "NullLabel_placeholder"]
}
) ; Look out. Above 5 lines are AHK strings, not AHK statements. Don't reformat it casually.
strlabels := ""
for i,label in arAutoexecLabels
{
; Prepare each line as an AutoexecForExe.labels[] element, as ahk array definition syntax.
strlabels .= Format("`t`t, ""{}""`r`n", label.label)
}
autogen_content := Format(autogen_content_fmt, strlabels)
dev_WriteWholeFile(gc_AutoexecLabelsFilepath, autogen_content)
}
amhk_IsAutoGlobalFilename(filenam)
{
if(not filenam ~= ".ahk$" )
return false
if(filenam==A_ScriptName)
return false ; skip self
if(filenam==gc_customize_ahk)
return false ; leave this at end
if(InStr(filenam, " "))
return false ; reject those with spaces in filename
return true
}
amhk_CallAutoexecLabels(arAutoexecLabels)
{
module_count := 0
msglistmodules := ""
for index, autolabel in arAutoexecLabels
{
dict_DoneLabels := {}
label_varname := autolabel.label
if(!dict_DoneLabels.HasKey(label_varname) && IsLabel(label_varname))
{
dict_DoneLabels[label_varname] := true
module_count++
msglistmodules .= module_count ". " autolabel.filename " [" label_varname "]`n"
; Jump to one AUTOEXEC_xxx_ahk label:
;
GoSub, %label_varname%
}
else
{
; This label_varname is not found, probably because its containing XXX.ahk
; is not included in _more_includes_.ahk .
}
}
if(module_count==0) ; no modules loaded, probably _more_includes_.ahk not generated yet
{
srcfile := Format("{}\{}", A_ScriptDir, "_more_includes_.ahk.sample")
dstfile := Format("{}\{}", A_ScriptDir, "_more_includes_.ahk")
; MsgBox, % Format("filecopy {} -- {}", srcfile, dstfile)
FileCopy, %srcfile%, %dstfile%
if(ErrorLevel)
{
dev_MsgBoxError(Format("Cannot find or generate ""{}"" . The program will exit.", dstfile))
ExitApp, 4
}
; Generate customize.ahk from customize.ahk.sample as well
dst_customize_ahk := A_ScriptDir "\customize.ahk"
FileCopy, % A_ScriptDir "\customize.ahk.sample" , % dst_customize_ahk , 0 ; no overwrite
if(!FileExist(dst_customize_ahk))
{
dev_MsgBoxWarning("Cannot create file: " dst_customize_ahk)
}
MsgBox, % msgboxoption_IconInfo, % "AmHotkey.ahk starts",
(
This is the first time you run this script.
You can edit
%dstfile%
to customize what AHK modules to load into this program.
Click OK to continue.
)
Reload
}
;
start_msgbox_info =
(
%A_ScriptDir%\%A_ScriptName% has loaded the following modules:`n
%msglistmodules%
)
dev_MsgBoxInfo(start_msgbox_info, "AmHotkey script loading info")
}
#!s:: Launch_AU3Spy()
Launch_AU3Spy()
{
tooltip
if not A_AhkPath {
MsgBox, A_AhkPath is blank, so I don't know where to find AU3_Spy.exe
}
spypath := RegExReplace(A_AhkPath, "(.+)\\[^\\]+$", "$1\AU3_Spy.exe")
Run, %spypath%, , UseErrorLevel
if ErrorLevel {
MsgBox, "%spypath%" launch failed!
}
else {
winspy_class := "ahk_class AutoHotkeyGUI"
WinWait, %winspy_class%
WinActivate, %winspy_class%
WinWaitActive, %winspy_class%
}
}
Get_DPIScale()
{
return A_ScreenDPI/96
}
FlashRectInActiveWindow(x, y, width, height) ; old test code
{
speed = 10, sleep = 100
tooltip, ☆ , % x, % y
mousemove, % x , % y , 1
sleep, %sleep%
mousemove, % x, % y+height , %speed%
sleep, %sleep%
mousemove, % x+width, % y+height , %speed%
sleep, %sleep%
mousemove, % x+width, % y , %speed%
sleep, %sleep%
mousemove, % x, % y , %speed%
tooltip, ★ , % x+width, % y+height
}
HighlightRectInScreen(screenx, screeny, width, height, rgb:="8000FF", duration_msec:=2000) ; "8000FF"=purple
{
Gui, hilightScreen:New
Gui, hilightScreen:-Caption +ToolWindow ; so that it can be transparent
Gui, hilightScreen:+HwndHRwnd ; generate variable HRwnd
Gui, hilightScreen:Color, % rgb
Gui, hilightScreen:Font, s8 c888888, Tahoma
Gui, hilightScreen:Add, Text, , AHK Highlight
;
showopt := "X" . screenx . " Y" . screeny . " W" . width . " H" . height
Gui, hilightScreen:Show, %showopt%
WinSet, AlwaysOnTop, On, ahk_id %HRwnd%
WinSet, Transparent, 160, ahk_id %HRwnd%
;
SetTimer, hilightScreenGuiEscape, -%duration_msec%
return
hilightScreenGuiClose:
hilightScreenGuiEscape:
; tooltip timer...END (A_Gui=%A_Gui% A_GuiControl=%A_GuiControl%)
Gui, hilightScreen:Destroy
return
}
HighlightRectInActiveWindow(hx, hy, hwidth, hheight, duration_msec:=2000) ; old code, use DoHilightRectInTopwin instead
{
; hx, hy relative to current active window
WinGetPos, Ax, Ay, Awidth, Aheight, A
Gui, hilightwin:New
Gui, hilightwin:-Caption +ToolWindow ; so that it can be transparent
Gui, hilightwin:+HwndHRwnd ; generate variable HRwnd
Gui, hilightwin:Color, FFFF00
Gui, hilightwin:Font, s8 c888888, Tahoma
Gui, hilightwin:Add, Text, , AHK Highlight
;
screenx := Ax + hx
screeny := Ay + hy
showopt := "X" . screenx . " Y" . screeny . " W" . hwidth . " H" . hheight
Gui, hilightwin:Show, %showopt%
WinSet, AlwaysOnTop, On, ahk_id %HRwnd%
WinSet, Transparent, 200, ahk_id %HRwnd%
;
SetTimer, hilightwinGuiEscape, -%duration_msec%
return
hilightwinGuiClose:
hilightwinGuiEscape:
; tooltip timer...END (A_Gui=%A_Gui% A_GuiControl=%A_GuiControl%)
Gui, hilightwin:Destroy
return
}
DoHilightRectInTopwin(wintitle, x, y, w, h, duration_msec:=1000, rgb:="FFE0BE")
{
arRects := [ { "x":x, "y":y, "w":w, "h":h, "rgb":rgb, "notext":true} ]
DoHilightBlocksInTopwin(wintitle, arRects, duration_msec)
}
DoHilightBlocksInTopwin(wintitle, arRects, msec_step:=1000)
{
; arRects is an array; array element is a dict with member .x .y .w .h
WinGet, hwndBase, ID, %wintitle%
static ccyellow := "FFFF00" , ccred := "FF8888" , ccmagenta := "FF00FF" ; cc: color code
static hilictl := {}
static s_hili_running := false
if (s_hili_running) {
tooltip, Another instance of DoHilightBlocksInTopwin is running.
return
}
s_hili_running := true
static s_name := ""
global HiliText
; must be global, otherwise, second timer's will GuiControl will not update control text
; The manual explicitly states this in "Functions -> Using Subroutines Within a Function"
hilictl := {}
hilictl.wintitle := wintitle
; hilictl.name := "hiname" ; optional
hilictl.msec_step := msec_step
hilictl.nextstep := 1
hilictl.arsteps := arRects
; hx, hy relative to current active window
WinGetPos, Ax, Ay, Awidth, Aheight, A
Gui, hiliblock:New
Gui, hiliblock:-Caption +ToolWindow ; so that it can be transparent
Gui, hiliblock:+HwndHIwnd ; generate variable HIwnd (global or local? seems global)
; Gui, hiliblock:Color, %ccyellow% ; set later
Gui, hiliblock:Font, s8 c333333, Tahoma
Gui, hiliblock:Add, Text, vHiliText, "any" ; text modified later
hilictl.HIwnd := HIwnd
hilictl.hwndBase := hwndBase
GoSub, HiliStepTimer ; Starting the highlight!
; Wait until all hilight done
while (s_hili_running)
sleep 100
return
hiliblockGuiClose:
hiliblockGuiEscape:
; tooltip, % "close " . hilictl.nextstep
HiliStepTimer:
arsteps := hilictl.arsteps ; each step is an object containing xywh(4 members)
thisstep := hilictl.nextstep
hilictl.nextstep += 1
maxsteps := arsteps.MaxIndex()
thisrect := arsteps[thisstep]
if(thisstep>maxsteps)
{
; kill timer
SetTimer, HiliStepTimer, Off
Gui, hiliblock:Destroy
s_hili_running := false
return
}
WinGetPos, xbase, ybase, wbase, hbase, % "ahk_id " hilictl.hwndBase
boxcolor := thisrect.rgb ? thisrect.rgb : ccyellow
halfw := 200, halfh := 100
; Check Rect validity:
is_goodwnd := true ; assume true
;
if(xbase=="" || ybase=="")
{
is_goodwnd := false
; Will display a RED box at center of the main monitor warning the user
x := A_ScreenWidth/2 - halfw
y := A_ScreenHeight/2 - halfh
w := halfw * 2
h := halfh * 2
boxtext := "Can not get valid HWND by AHK wintitle:`n`n" . hilictl.wintitle
. "`n`nPress cancel to dismiss."
}
else if(thisrect.x=="" || thisrect.y=="" || thisrect.w=="" || thisrect.h=="")
{
is_goodwnd := false
x := xbase
y := ybase
w := halfw * 2
h := halfh * 2
boxtext := "Invalid xywh input.`n`n"
. "x=" . thisrect.x . " y=" . thisrect.y . " w=" . thisrect.w . " h=" . thisrect.h
. "`n`nPress cancel to dismiss."
}
else
{
if(thisrect.w>0 && thisrect.h>0)
{
x := thisrect.x + xbase
y := thisrect.y + ybase
w := thisrect.w
h := thisrect.h
boxtext := "x=" . thisrect.x . " y=" . thisrect.y . "`n[w=" . thisrect.w . " h=" . thisrect.h . "]"
; display x,y relative to the topmost window
}
else
{
x := thisrect.x + xbase
y := thisrect.y + ybase
w := 200
h := 200
boxcolor := thisrect.rgb ? thisrect.rgb : ccmagenta
boxtext := "Invisible! w=" . thisrect.w . " h=" . thisrect.h
}
if(maxsteps>1)
boxtext := thisstep . "/" . maxsteps . ": " . boxtext
}
if(not is_goodwnd)
boxcolor := thisrect.rgb ? thisrect.rgb : ccred
if(thisrect.notext)
boxtext := ""
Gui, hiliblock:Color, %boxcolor%
GuiControl, hiliblock:, HiliText, %boxtext%
GuiControl, hiliblock:Move, HiliText, X0 Y0 w%w% h%h% ; this is relative to HIwnd
Gui, hiliblock:Show, X0 Y0 W20 H10 ; init arbitrary small window
; Don't use %screen_xywh% in Gui,Show (its W,H means client area), so use WinMove .
HIwnd := hilictl.HIwnd ; optional, because HIwnd has been a global
WinMove, % "ahk_id " . HIwnd,
, % xbase+thisrect.x , ybase+thisrect.y, % w, % h
WinSet, AlwaysOnTop, On, ahk_id %HIwnd%
if(is_goodwnd)
{
WinSet, Transparent, 188, ahk_id %HIwnd% ; set-transparent must be AFTER Gui,Show , no effect otherwise
SetTimer, HiliStepTimer, % 0-hilictl.msec_step
}
else
{
WinSet, Transparent, 244, ahk_id %HIwnd%
hilictl.nextstep := maxsteps+1 ; so that next callback will destroy the Gui
SetTimer, HiliStepTimer, Off ; so user have to explicitly close the box (keyboard cancel)
}
return
}
;##############################################################################
;#################### Environment checking functions ##########################
;##############################################################################
GetMonitorWorkArea(monidx)
{
; monidx 1 means first monitor, 2 means second ...
; SysGet, wa, Monitor, %monidx%
SysGet, wa, MonitorWorkArea, %monidx% ; this exlcudes taskbar region
if(waLeft!=None)
{
return {"left":waLeft, "right":waRight, "top":waTop, "bottom":waBottom
, "width":waRight-waLeft, "height":waBottom-waTop }
}
else
return None
}
; ===============================================================================================
dbgHotkeyFlex(msg)
{
AmDbg_output(AmHotkey.dbgid_HotkeyFlex, msg)
}
dbgHotkeyLegacy(msg)
{
AmDbg_output(AmHotkey.dbgid_HotkeyLegacy, msg)
}
_fxhk_KeynameStripPrefix(keyname)
{
; Purpose: On Autohotkey 1.1.36 and many prior versions, I see that, when a Hotkey callback
; is called, the A_ThisHotkey is not exactly the same as when we formerly told `Hotkey` command.
; For example "$NumpadDiv" becomes "NumpadDiv", but "$NumpadLeft" remains "$NumpadLeft".
; So, we need to strip off "~" and "$", and use the stripped-off form as dict-key to
; Amhk.HotkeyFlexDispatcher .
keyname := dev_StripPrefixChars(keyname, "~$")
return keyname
}
_fxhk_KeynameAddHppPrefix(keyname)
{
if(_fxhk_IsComboKeyname(keyname))
{
; User assigns a "Custom combination" keyname (CcHotkey) like "Esc & 1",
; then we need to add ~ prefix,
; so that Esc key's native action is not blocked (=keepnative).
return "~" keyname
}
else
{
; User assigns a keyname like "F1", and we need to add $ prefix,
; so that we can delay-determine whether to passthru this hotkey.
return "$" keyname
}
}
_fxhk_IsComboKeyname(keyname, byref prefix_keyname="", byref suffix_keyname:="")
{
if(InStr(keyname, " & "))
{
dual := StrSplit(keyname, " & ")
prefix_keyname := dual[1]
suffix_keyname := dual[2]
return true
}
else
{
return false
}
}
; [2023-01-06] Brandnew dynamic hotkey definition.
; User can attach multiple actions to the same [hotkey-and-condition pair].
; User parameter fn_cond and fn_act, can be any "callable" variable, which include:
; * a string representing a function name, or
; * a function object, ( via Func("somefuncname") )
; * a BoundFunc object. // (to final-confirm)
;
; fn_cond: The condition to run fn_act. If fn_cond=="", then fn_act is always run.
_in_dev_DefineHotkeyFlex(user_keyname, purpose_name, comment, is_passthru, fn_cond, fn_act, act_args*)
{
; user_keyname is the "KeyName" param that can be passed to `Hotkey` internal command.
; e.g., "F1"
; Check input param validity >>>
if(StrLen(fn_cond)>0)
{
errmsg := Format("ERROR on 'fn_cond' param: ""{}"" is not a string representing a function name.", fn_cond)
dev_assert(dev_IsExistingFuncName(fn_cond), errmsg)
}
if(comment!="_off_")
{
errmsg := Format("ERROR on 'fn_act' param: ""{}"" is not a string representing a function name.", fn_act)
dev_assert(dev_IsExistingFuncName(fn_act), errmsg)
}
; Check input param validity <<<
is_add := comment!="_off_" ? true : false
dev_assert(user_keyname!="")
if(is_add)
dev_assert(fn_act!="")
if(user_keyname=="" || (is_add && fn_act==""))
return ""
s_dp := Amhk.HotkeyFlexDispatcher ; the static global
; Data structure example:
;
; s_dp["F1"]["purpose_auto1"].comment
; s_dp["F1"]["purpose_auto1"].fn_cond
; s_dp["F1"]["purpose_auto1"].fn_act
; s_dp["F1"]["purpose_auto1"].act_args
;
; s_dp["F1"]["purpose_auto2"].comment
; s_dp["F1"]["purpose_auto2"].fn_cond
; s_dp["F1"]["purpose_auto2"].fn_act
; s_dp["F1"]["purpose_auto2"].act_args
; If purpose_name is null, a new purpose_name will be auto-generated.
; If purpose_name is not null, old purpose_name will be replaced.
;
; If `comment` is "_off_", the hotkey by [keyname-purpose_name] is to be removed.
; Note: $ and ~ keyname prefixes are ignored by _in_dev_DefineHotkeyFlex(),
; bcz $ and ~ is incompatible with _in_dev_DefineHotkeyFlex() intrinsic logic.
; Workaround: To make a Hotkey do it original work(the work when AHK is not run),
; user should set param is_passthru=true. If user registers multiple fn_act-s
; on the same Hotkey, any is_passthru=true makes it true.
;
keynamed := _fxhk_KeynameStripPrefix(user_keyname) ; keyname as dict-key
hpp_keyname := _fxhk_KeynameAddHppPrefix(keynamed) ; hpp: hook($) or passthru(~) prefix
dbgHotkeyFlex(Format("user_keyname=〖{}〗, keynamed=〖{}〗, hpp_keyname=〖{}〗", user_keyname, keynamed, hpp_keyname))
if(is_add)
{
; create first-level object for keynamed
if(not s_dp[keynamed])
{
dbgHotkeyFlex(Format("Create empty object s_dp[""{}""]", keynamed))
s_dp[keynamed] := {}
}
if(purpose_name=="")
purpose_name := _create_auto_purposename(s_dp[keynamed])
is_new_purpose := not s_dp[KeyNamed].HasKey(purpose_name)
dbgHotkeyFlex( Format("{} hotkey 〖{}〗 of purpose-name: ""{}""`r`n"
. " .is_passthru = {}`r`n"
. " .comment = {}`r`n"
. " .fn_cond = {}`r`n"
. " .fn_act = {}`r`n"
. " .act_args (count) = {}"
, (is_new_purpose?"Create":"Update"), keynamed, purpose_name