forked from 7plus/7plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiscFunctions.ahk
2096 lines (1944 loc) · 72.3 KB
/
MiscFunctions.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
;This file contains various functions for all kinds of things. YAY!
#include *i %A_ScriptDir%\lib\Array.ahk
;Gets a localized string from a resource file.
;usage example:
;x := TranslateMUI("shell32.dll",31236)
TranslateMUI(resDll, resID)
{
VarSetCapacity(buf, 256)
hDll := DllCall("LoadLibrary", "str", resDll, "Ptr")
Result := DllCall("LoadString", "Ptr", hDll, "uint", resID, "str", buf, "int", 128)
return buf
}
;Finds the path of the Shell32.dll.mui file
LocateShell32MUI()
{
VarSetCapacity(buffer, 85*2)
length:=DllCall("GetUserDefaultLocaleName","UIntP",buffer,"UInt",85)
if(A_IsUnicode)
locale := StrGet(buffer)
shell32MUIpath := A_WinDir "\winsxs\*_microsoft-windows-*resources*" locale "*" ;\x86_microsoft-windows-shell32.resources_31bf3856ad364e35_6.1.7600.16385_de-de_b08f46c44b512da0\shell32.dll.mui
loop %shell32MUIpath%,2,0
if(FileExist(A_LoopFileFullPath "\shell32.dll.mui"))
return A_LoopFileFullPath "\shell32.dll.mui"
}
;Splits a command into command and arguments
SplitCommand(fullcmd, ByRef cmd, ByRef args)
{
if(InStr(fullcmd, """") = 1)
{
pos := InStr(fullcmd, """" , 0, 2)
cmd := SubStr(fullcmd, 2,pos - 2)
args := SubStr(fullcmd, pos + 1)
args := strTrim(args, " ")
}
else if(pos:=InStr(fullcmd, " " , 0, 1))
{
cmd := SubStr(fullcmd, 1, pos-1)
args := SubStr(fullcmd, pos+1)
args := strTrim(args, " ")
}
else
{
cmd := fullcmd
args := ""
}
}
;Gets a free gui number.
/* Group: About
o v0.81 by majkinetor.
o Licenced under BSD <http://creativecommons.org/licenses/BSD/>
*/
GetFreeGuiNum(start, prefix = ""){
loop
{
Gui %prefix%%start%:+LastFoundExist
IfWinNotExist
return prefix start
start++
if(start = 100)
return 0
}
return 0
}
;Checks if a specific window is under the cursor.
IsWindowUnderCursor(hwnd)
{
MouseGetPos, , , win
if hwnd is number
return win = hwnd
else
return InStr(WinGetClass("ahk_class " win), hwnd)
}
;Checks if a specific control is under the cursor and returns its ClassNN if it is.
IsControlUnderCursor(ControlClass)
{
MouseGetPos, , , , control
if(InStr(Control, ControlClass))
return control
return false
}
;Sets window event hook
API_SetWinEventHook(eventMin, eventMax, hmodWinEventProc, lpfnWinEventProc, idProcess, idThread, dwFlags) {
return DllCall("SetWinEventHook", "uint", eventMin, "uint", eventMax, "Ptr", hmodWinEventProc, "uint", lpfnWinEventProc, "uint", idProcess, "uint", idThread, "uint", dwFlags, "Ptr")
}
;Unhooks window event hook
API_UnhookWinEvent( hWinEventHook ) {
return DllCall("UnhookWinEvent", "Ptr", hWinEventHook)
}
;disables or restores original minimize anim setting
DisableMinimizeAnim(disable)
{
static original,lastcall
if(disable && !lastcall) ;Backup original value if disabled is called the first time after a restore call
{
lastcall := 1
RegRead, original, HKCU, Control Panel\Desktop\WindowMetrics , MinAnimate
}
else if(!disable) ;this is a restore call, on next disable backup may be created again
lastcall := 0
;Disable Minimize/Restore animation
VarSetCapacity(struct, 8, 0)
NumPut(8, struct, 0, "UInt")
if(disable || !original)
NumPut(0, struct, 4, "Int")
else
NumPut(1, struct, 4, "UInt")
DllCall("SystemParametersInfo", "UINT", 0x0049,"UINT", 8,"Ptr", &struct,"UINT", 0x0003) ;SPI_SETANIMATION 0x0049 SPIF_SENDWININICHANGE 0x0002
}
/*
Performs a hittest on the window under the mouse and returns the WM_NCHITTEST Result
#define HTERROR (-2)
#define HTTRANSPARENT (-1)
#define HTNOWHERE 0
#define HTCLIENT 1
#define HTCAPTION 2
#define HTSYSMENU 3
#define HTGROWBOX 4
#define HTSIZE HTGROWBOX
#define HTMENU 5
#define HTHSCROLL 6
#define HTVSCROLL 7
#define HTMINBUTTON 8
#define HTMAXBUTTON 9
#define HTLEFT 10
#define HTRIGHT 11
#define HTTOP 12
#define HTTOPLEFT 13
#define HTTOPRIGHT 14
#define HTBOTTOM 15
#define HTBOTTOMLEFT 16
#define HTBOTTOMRIGHT 17
#define HTBORDER 18
#define HTREDUCE HTMINBUTTON
#define HTZOOM HTMAXBUTTON
#define HTSIZEFIRST HTLEFT
#define HTSIZELAST HTBOTTOMRIGHT
#if(WINVER >= 0x0400)
#define HTOBJECT 19
#define HTCLOSE 20
#define HTHELP 21
*/
MouseHitTest()
{
CoordMode, Mouse, Screen
MouseGetPos, MouseX, MouseY, WindowUnderMouseID
WinGetClass, winclass , ahk_id %WindowUnderMouseID%
if winclass in BaseBar,D2VControlHost,Shell_TrayWnd,WorkerW,ProgMan ; make sure we're not doing this on the taskbar
return -2
; WM_NCHITTEST
SendMessage, 0x84,, ( (MouseY&0xFFFF) << 16 )|(MouseX&0xFFFF),, ahk_id %WindowUnderMouseID%
return ErrorLevel
}
;Returns true if there is an available internet connection
IsConnected(URL="http://code.google.com/p/7plus/")
{
return DllCall("Wininet.dll\InternetCheckConnection", "Str", URL,"UInt", 1, "UInt",0, "UInt")
}
/*! TheGood (modified a bit by Fragman)
Checks if a window is in fullscreen mode.
______________________________________________________________________________________________________________
sWinTitle - WinTitle of the window to check. Same syntax as the WinTitle parameter of, e.g., WinExist().
bRefreshRes - Forces a refresh of monitor data (necessary if resolution has changed)
UseExcludeList - returns false if window class is in FullScreenExclude (explorer, browser etc)
UseIncludeList - returns true if window class is in FullScreenInclude (applications capturing gamepad input)
Return value o If window is fullscreen, returns the index of the monitor on which the window is fullscreen.
o If window is not fullscreen, returns False.
ErrorLevel - Sets ErrorLevel to True if no window could match sWinTitle
Based on the information found at http://support.microsoft.com/kb/179363/ which discusses under what
circumstances does a program cover the taskbar. Even if the window passed to IsFullscreen is not the
foreground application, IsFullscreen will check if, were it the foreground, it would cover the taskbar.
*/
IsFullscreen(sWinTitle = "A", UseExcludeList = true, UseIncludeList=true) {
Static
Local iWinX, iWinY, iWinW, iWinH, iCltX, iCltY, iCltW, iCltH, iMidX, iMidY, iMonitor, c, D, iBestD
ErrorLevel := False
;Without admin mode processes launched with admin permissions aren't detectable, so better treat all windows as non-fullscreen.
if(!A_IsAdmin)
return false
;Get the active window's dimension
hWin := WinExist(sWinTitle)
If Not hWin {
ErrorLevel := True
Return False
}
;Make sure it's not desktop
WinGetClass, c, ahk_id %hWin%
If (hWin = DllCall("GetDesktopWindow", "Ptr") Or (c = "Progman") Or (c = "WorkerW"))
Return False
;Fullscreen include list
if(UseIncludeList)
{
FullscreenInclude := Settings.Misc.FullScreenInclude
if c in %FullscreenInclude%
return true
}
;Fullscreen exclude list
if(UseExcludeList)
{
FullscreenExclude := Settings.Misc.FullScreenExclude
if c in %FullscreenExclude%
return false
}
;Resolution change would only need to be detected every few seconds or so, but since it doesn't add anything notably to cpu usage, just do it always
SysGet, Mon0, MonitorCount
SysGet, iPrimaryMon, MonitorPrimary
Loop %Mon0% { ;Loop through each monitor
SysGet, Mon%A_Index%, Monitor, %A_Index%
Mon%A_Index%MidX := Mon%A_Index%Left + Ceil((Mon%A_Index%Right - Mon%A_Index%Left) / 2)
Mon%A_Index%MidY := Mon%A_Index%Top + Ceil((Mon%A_Index%Top - Mon%A_Index%Bottom) / 2)
}
;Get the window and client area, and style
VarSetCapacity(iWinRect, 16), VarSetCapacity(iCltRect, 16)
DllCall("GetWindowRect", "Ptr", hWin, "Ptr", &iWinRect)
DllCall("GetClientRect", "Ptr", hWin, "Ptr", &iCltRect)
WinGet, iStyle, Style, ahk_id %hWin%
;Extract coords and sizes
iWinX := NumGet(iWinRect, 0), iWinY := NumGet(iWinRect, 4)
iWinW := NumGet(iWinRect, 8) - NumGet(iWinRect, 0) ;Bottom-right coordinates are exclusive
iWinH := NumGet(iWinRect, 12) - NumGet(iWinRect, 4) ;Bottom-right coordinates are exclusive
iCltX := 0, iCltY := 0 ;Client upper-left always (0,0)
iCltW := NumGet(iCltRect, 8), iCltH := NumGet(iCltRect, 12)
; Debug("iCltW " iCltW " iCltH " iCltH)
;Check in which monitor it lies
iMidX := iWinX + Ceil(iWinW / 2)
iMidY := iWinY + Ceil(iWinH / 2)
;Loop through every monitor and calculate the distance to each monitor
iBestD := 0xFFFFFFFF
Loop % Mon0 {
D := Sqrt((iMidX - Mon%A_Index%MidX)**2 + (iMidY - Mon%A_Index%MidY)**2)
If (D < iBestD) {
iBestD := D
iMonitor := A_Index
}
}
;Check if the client area covers the whole screen
bCovers := (iCltX <= Mon%iMonitor%Left) And (iCltY <= Mon%iMonitor%Top) And (iCltW >= Mon%iMonitor%Right - Mon%iMonitor%Left) And (iCltH >= Mon%iMonitor%Bottom - Mon%iMonitor%Top)
If(bCovers)
Return True
;Check if the window area covers the whole screen and styles
bCovers := (iWinX <= Mon%iMonitor%Left) And (iWinY <= Mon%iMonitor%Top) And (iWinW >= Mon%iMonitor%Right - Mon%iMonitor%Left) And (iWinH >= Mon%iMonitor%Bottom - Mon%iMonitor%Top)
If (bCovers) ;WS_THICKFRAME or WS_CAPTION
{
bCovers &= Not (iStyle & 0x00040000) Or Not (iStyle & 0x00C00000)
Return bCovers ? iMonitor : False
}
Else
Return False
}
;Returns the workspace area covered by the active monitor
GetActiveMonitorWorkspaceArea(ByRef MonLeft, ByRef MonTop, ByRef MonW, ByRef MonH,hWndOrMouseX, MouseY = "")
{
mon := GetActiveMonitor(hWndOrMouseX, MouseY)
if(mon>=0)
{
SysGet, Mon, MonitorWorkArea, %mon%
MonW := MonRight - MonLeft
MonH := MonBottom - MonTop
}
}
;Returns the monitor the mouse or the active window is in
GetActiveMonitor(hWndOrMouseX, MouseY = "")
{
if(MouseY="")
{
WinGetPos,x,y,w,h,ahk_id %hWndOrMouseX%
if(!x && !y && !w && !h)
{
MsgBox GetActiveMonitor(): invalid window handle!
return -1
}
x := x + Round(w/2)
y := y + Round(h/2)
}
else
{
x := hWndOrMouseX
y := MouseY
}
;Loop through every monitor and calculate the distance to each monitor
iBestD := 0xFFFFFFFF
SysGet, Mon0, MonitorCount
Loop %Mon0% { ;Loop through each monitor
SysGet, Mon%A_Index%, Monitor, %A_Index%
Mon%A_Index%MidX := Mon%A_Index%Left + Ceil((Mon%A_Index%Right - Mon%A_Index%Left) / 2)
Mon%A_Index%MidY := Mon%A_Index%Top + Ceil((Mon%A_Index%Top - Mon%A_Index%Bottom) / 2)
}
Loop % Mon0 {
D := Sqrt((x - Mon%A_Index%MidX)**2 + (y - Mon%A_Index%MidY)**2)
If (D < iBestD) {
iBestD := D
iMonitor := A_Index
}
}
return iMonitor
}
;Returns the (signed) minimum of the absolute values of x and y
absmin(x,y)
{
return abs(x) > abs(y) ? y : x
}
;Returns the (signed) maximum of the absolute values of x and y
absmax(x,y)
{
return abs(x) < abs(y) ? y : x
}
;Returns 1 if x is positive or 0 and -1 if x is negative
sign(x)
{
return x < 0 ? -1 : 1
}
;returns the maximum of xdir and y, but with the sign of xdir
dirmax(xdir,y)
{
if(xdir = 0)
return 0
if(abs(xdir) > y)
return xdir
return xdir / abs(xdir) * abs(y)
}
;returns the maximum of xdir and y, but with the sign of xdir
dirmin(xdir,y)
{
if(xdir = 0)
return 0
if(abs(xdir) < y)
return xdir
return xdir / abs(xdir) * abs(y)
}
;Formats a number in hexadecimal
DecToHex( ByRef var )
{
f := A_FormatInteger
SetFormat, Integer, Hex
var += 0
; SetFormat, Integer, %f%
return var
}
;Determines if a string starts with another string. NOTE: It's a bit faster to simply use InStr(string, start) = 1
strStartsWith(string,start)
{
return InStr(string, start) = 1
}
;Determines if a string ends with another string
strEndsWith(string, end)
{
return strlen(end) <= strlen(string) && Substr(string, -strlen(end) + 1) = end
}
;Removes all occurences of trim at the beginning and end of string
;trim can be an array of strings that should be removed.
strTrim(string, trim)
{
return strTrimLeft(strTrimRight(string, trim), trim)
}
;Removes all occurences of trim at the beginning of string
;trim can be an array of strings that should be removed.
strTrimLeft(string, trim)
{
if(!IsObject(trim))
trim := [trim]
for index, trimString in trim
{
len := strLen(trimString)
while(InStr(string, trimString) = 1)
StringTrimLeft, string, string, %len%
}
return string
}
;Removes all occurences of trim at the end of string
;trim can be an array of strings that should be removed.
strTrimRight(string, trim)
{
if(!IsObject(trim))
trim := [trim]
for index, trimString in trim
{
len := strLen(trimString)
while(strEndsWith(string, trimString))
StringTrimRight, string, string, %len%
}
return string
}
;Finds the first window matching specific criterias.
FindWindow(title, class="", style="", exstyle="", processname="", allowempty = false)
{
WinGet, id, list,,, Program Manager
Loop, %id%
{
this_id := id%A_Index%
WinGetClass, this_class, ahk_id %this_id%
if(class && class!=this_class)
Continue
WinGetTitle, this_title, ahk_id %this_id%
if(title && title!=this_title)
Continue
WinGet, this_style, style, ahk_id %this_id%
if(style && style!=this_style)
Continue
WinGet, this_exstyle, exstyle, ahk_id %this_id%
if(exstyle && exstyle!=this_exstyle)
Continue
WinGetPos ,,,w,h,ahk_id %this_id%
if(!allowempty && (w=0 || h=0))
Continue
WinGet, this_processname, processname, ahk_id %this_id%
if(processname && processname!=this_processname)
Continue
return this_id
}
return 0
}
;Gets the process name from a window handle.
GetProcessName(hwnd)
{
WinGet, ProcessName, processname, ahk_id %hwnd%
return ProcessName
}
;Gets the path of a process by its pid
GetModuleFileNameEx(pid)
{
if A_OSVersion in WIN_95,WIN_98,WIN_ME
{
MsgBox, This Windows version (%A_OSVersion%) is not supported.
return
}
/*
#define PROCESS_VM_READ (0x0010)
#define PROCESS_QUERY_INFORMATION (0x0400)
*/
h_process := DllCall("OpenProcess", "uint", 0x10|0x400, "int", false, "uint", pid, "Ptr")
if (ErrorLevel || h_process = 0)
{
Debug("[OpenProcess] failed. PID = " pid)
return
}
name_size := A_IsUnicode ? 510 : 255
VarSetCapacity(name, name_size)
result := DllCall("psapi.dll\GetModuleFileNameEx", "Ptr", h_process, "uint", 0, "str", name, "uint", name_size)
if(ErrorLevel || result = 0)
Debug("[GetModuleFileNameExA] failed")
DllCall("CloseHandle", "Ptr", h_process)
return name
}
; Extract an icon from an executable, DLL or icon file.
ExtractIcon(Filename, IconNumber = 0, IconSize = 64)
{
; LoadImage is not used..
; ..with exe/dll files because:
; it only works with modules loaded by the current process,
; it needs the resource ordinal (which is not the same as an icon index), and
; ..with ico files because:
; it can only load the first icon (of size %IconSize%) from an .ico file.
; If possible, use PrivateExtractIcons, which supports any size of icon.
; r:=DllCall("PrivateExtractIcons" , "str", Filename, "int", IconNumber-1, "int", IconSize, "int", IconSize, "Ptr*", h_icon, "PTR*", 0, "uint", 1, "uint", 0, "int")
;if !ErrorLevel
; return h_icon
r := DllCall("Shell32.dll\SHExtractIconsW", "str", Filename, "int", IconNumber-1, "int", IconSize, "int", IconSize, "Ptr*", h_icon, "Ptr*", pIconId, "uint", 1, "uint", 0, "int")
If (!ErrorLevel && r != 0)
return h_icon
return 0
}
;Gets the visible window at a screen coordinate
GetVisibleWindowAtPoint(x, y, IgnoredWindow)
{
DetectHiddenWindows,off
WinGet, id, list,,,
Loop, %id%
{
this_id := id%A_Index%
;WinActivate, ahk_id %this_id%
WinGetClass, this_class, ahk_id %this_id%
WinGetPos , WinX, WinY, Width, Height, ahk_id %this_id%
if(IsInArea(x, y, WinX, WinY, Width, Height) && this_class != IgnoredWindow)
{
DetectHiddenWindows, on
return this_class
}
}
DetectHiddenWindows,on
}
;checks if a point is in a rectangle
IsInArea(px, py, x, y, w, h)
{
return (px > x && py > y && px < x + w && py < y + h)
}
;Checks if two rectangles overlap
RectsOverlap(x1, y1, w1, h1, x2, y2, w2, h2)
{
Union := RectUnion(x1, y1, w1, h1, x2, y2, w2, h2)
return Union.w && Union.h
}
;Checks if two rectangles are separate
RectsSeparate(x1, y1, w1, h1, x2, y2, w2, h2)
{
Union := RectUnion(x1, y1, w1, h1, x2, y2, w2, h2)
return Union.w = 0 && Union.h = 0
}
;Check if the first rectangle includes the second one
RectIncludesRect(x1, y1, w1, h1, ix, iy, iw, ih)
{
Union := RectUnion(x1, y1, w1, h1, ix, iy, iw, ih)
return Union.x = ix && Union.y = iy && Union.w = iw && Union.h = ih
}
;Calculates the union of two rectangles
RectUnion(x1, y1, w1, h1, x2, y2, w2, h2)
{
x3 := ""
y3 := ""
;X Axis
if(x1 > x2 && x1 < x2 + w2)
x3 := x1
else if(x2 > x1 && x2 < x1 + w1)
x3 := x2
if(y1 > y2 && y1 < y2 + h2)
y3 := y1
else if(y2 > y1 && y2 < y1 + h1)
y3 := y2
if(x3 != x1 && x3 != x2) ;Not overlapping
w3 := 0
else
w3 := w1 - (x3 - x1) < w2 - (x3 - x2) ? w1 - (x3 - x1) : w2 - (x3 - x2) ;Choose the smaller width
if(y3 != y1 && y3 != y2) ;Not overlapping
h3 := 0
else
h3 := h1 - (y3 - y1) < h2 - (y3 - y2) ? h1 - (y3 - y1) : h2 - (y3 - y2) ;Choose the smaller height
if(w3 = 0)
h3 := 0
else if(h3 = 0)
w3 := 0
return Object("x", x3, "y", y3, "w", w3, "h", h3)
}
;Gets window position using workspace coordinates (-> no taskbar)
WinGetPlacement(hwnd, ByRef x="", ByRef y="", ByRef w="", ByRef h="", ByRef state="")
{
VarSetCapacity(wp, 44), NumPut(44, wp)
DllCall("GetWindowPlacement", "Ptr", hwnd, "Ptr", &wp)
x := NumGet(wp, 28, "int")
y := NumGet(wp, 32, "int")
w := NumGet(wp, 36, "int") - x
h := NumGet(wp, 40, "int") - y
state := NumGet(wp, 8, "UInt")
;Debug("get x" x " y" y " w" w " h" h " state " state)
}
;Sets window position using workspace coordinates (-> no taskbar)
WinSetPlacement(hwnd, x="",y="",w="",h="",state="")
{
WinGetPlacement(hwnd, x1, y1, w1, h1, state1)
if(x = "")
x := x1
if(y = "")
y := y1
if(w = "")
w := w1
if(h = "")
h := h1
if(state = "")
state := state1
VarSetCapacity(wp, 44), NumPut(44, wp)
if(state = 6)
NumPut(7, wp, 8) ;SW_SHOWMINNOACTIVE
else if(state = 1)
NumPut(4, wp, 8) ;SW_SHOWNOACTIVATE
else if(state = 3)
NumPut(3, wp, 8) ;SW_SHOWMAXIMIZED and/or SW_MAXIMIZE
else
NumPut(state, wp, 8)
NumPut(x, wp, 28, "Int")
NumPut(y, wp, 32, "Int")
NumPut(x+w, wp, 36, "Int")
NumPut(y+h, wp, 40, "Int")
DllCall("SetWindowPlacement", "Ptr", hwnd, "Ptr", &wp)
}
;Checks if the current LClick hotkey comes from a double click
IsDoubleClick()
{
return A_TimeSincePriorHotkey < DllCall("GetDoubleClickTime") && A_ThisHotkey=A_PriorHotkey
}
;Checks if a specific control class is active. Matches by start of ClassNN.
IsControlActive(controlclass)
{
if(WinVer >= WIN_7)
ControlGetFocus active, A
else
active := XPGetFocussed()
if(InStr(active, controlclass))
return true
return false
}
; This script retrieves the ahk_id (HWND) of the active window's focused control.
; This script requires Windows 98+ or NT 4.0 SP3+.
/*
typedef struct tagGUITHREADINFO {
DWORD cbSize;
DWORD flags;
HWND hwndActive;
HWND hwndFocus;
HWND hwndCapture;
HWND hwndMenuOwner;
HWND hwndMoveSize;
HWND hwndCaret;
RECT rcCaret;
} GUITHREADINFO, *PGUITHREADINFO;
*/
GetFocusedControl()
{
guiThreadInfoSize := 8 + 6 * A_PtrSize + 16
VarSetCapacity(guiThreadInfo, guiThreadInfoSize, 0)
NumPut(GuiThreadInfoSize, GuiThreadInfo, 0)
; DllCall("RtlFillMemory" , "PTR", &guiThreadInfo, "UInt", 1 , "UChar", guiThreadInfoSize) ; Below 0xFF, one call only is needed
If(DllCall("GetGUIThreadInfo" , "UInt", 0 ; Foreground thread
, "PTR", &guiThreadInfo) = 0)
{
ErrorLevel := A_LastError ; Failure
Return 0
}
focusedHwnd := NumGet(guiThreadInfo,8+A_PtrSize, "Ptr") ; *(addr + 12) + (*(addr + 13) << 8) + (*(addr + 14) << 16) + (*(addr + 15) << 24)
Return focusedHwnd
}
; Force kill program on Alt+F5 and on right click close button
CloseKill(hwnd)
{
WinGet, pid, pid, ahk_id %hwnd%
WinKill ahk_id %hwnd%
if(WinExist("ahk_id " hwnd))
Process, close, %pid%
}
/*
Converts a string list with separators to an array. It also removes and splits at quotes
To be parsed:
file a
file b
"file a"
"file b"
"file a" "file b"
"file a"|"file b"
file a|file b
*/
ToArray(SourceFiles, ByRef Separator = "`n", ByRef wasQuoted = 0)
{
if(IsArray(SourceFiles))
return SourceFiles
files := Array()
pos := 1
wasQuoted := 0
Loop
{
if(pos > strlen(SourceFiles))
break
char := SubStr(SourceFiles, pos, 1)
if(char = """" || wasQuoted) ;Quoted paths
{
file := SubStr(SourceFiles, InStr(SourceFiles, """", 0, pos) + 1, InStr(SourceFiles, """", 0, pos + 1) - pos - 1)
if(!wasQuoted)
{
wasQuoted := 1
Separator := SubStr(SourceFiles, InStr(SourceFiles, """", 0, pos + 1) + 1, InStr(SourceFiles, """", 0, InStr(SourceFiles, """", 0, pos + 1) + 1) - InStr(SourceFiles, """", 0, pos + 1) - 1)
}
if(file)
{
files.Insert(file)
pos += strlen(file) + 3
continue
}
else
Msgbox Invalid source format %SourceFiles%
}
else
{
file := SubStr(SourceFiles, pos, max(InStr(SourceFiles, Separator, 0, pos + 1) - pos, 0)) ; separator
if(!file)
file := SubStr(SourceFiles, pos) ;no quotes or separators, single file
if(file)
{
files.Insert(file)
pos += strlen(file) + strlen(Separator)
continue
}
else
Msgbox Invalid source format
}
pos++ ;Shouldn't happen
}
return files
}
;Flattens an array to a list with separators
ArrayToList(array, separator = "`n", quote = 0)
{
Loop % array.MaxIndex()
result .= (A_Index != 1 ? separator : "") (quote ? """" : "") array[A_Index] (quote ? """" : "")
return result
}
;Compares two (already separated) version numbers. Returns 1 if 1st is greater, 0 if equal, -1 if second is greater
CompareVersion(major1,major2,minor1,minor2,bugfix1,bugfix2)
{
if(major1 > major2)
return 1
else if(major1 = major2 && minor1 > minor2)
return 1
else if(major1 = major2 && minor1 = minor2 && bugfix1 > bugfix2)
return 1
else if(major1 = major2 && minor1 = minor2 && bugfix1 = bugfix2)
return 0
else
return -1
}
;Returns true if x is a number
IsNumeric(x)
{
If x is number
Return 1
Return 0
}
;Performs quote unescaping of a string. Transforms \" to " and \\ to \
StringUnescape(String)
{
return StringReplace(StringReplace(StringReplace(String, "\\", Chr(1), 1), "\""", """", 1), Chr(1), "\", 1)
}
;Performs quote escaping of a string. Transforms " to \" and \ to \\
StringEscape(String)
{
return StringReplace(StringReplace(String, "\", "\\", 1), """", "\""", 1)
}
;Decodes a URL
uriDecode(str) {
Loop
If RegExMatch(str, "i)(?<=%)[\da-f]{1,2}", hex)
StringReplace, str, str, `%%hex%, % Chr("0x" . hex), All
Else Break
Return, str
}
; modified from jackieku's code (http://www.autohotkey.com/forum/post-310959.html#310959)
UriEncode(str, Enc = "UTF-8")
{
try
{
oSC := ComObjCreate("ScriptControl")
oSC.Language := "JScript"
Script := "var Encoded = encodeURIComponent(""" . str . """)"
oSC.ExecuteStatement(Script)
encoded := oSC.Eval("Encoded")
Return encoded
}
catch e
{
StrPutVar(str, Var, Enc)
f := A_FormatInteger
SetFormat, IntegerFast, H
Loop
{
Code := NumGet(Var, A_Index - 1, "UChar")
If (!Code)
Break
If (Code >= 0x30 && Code <= 0x39 ; 0-9
|| Code >= 0x41 && Code <= 0x5A ; A-Z
|| Code >= 0x61 && Code <= 0x7A) ; a-z
Res .= Chr(Code)
Else
Res .= "%" . SubStr(Code + 0x100, -1)
}
SetFormat, IntegerFast, %f%
Return, Res
}
}
StrPutVar(Str, ByRef Var, Enc = "")
{
Len := StrPut(Str, Enc) * (Enc = "UTF-16" || Enc = "CP1200" ? 2 : 1)
VarSetCapacity(Var, Len, 0)
Return, StrPut(Str, &Var, Enc)
}
;Old function for codepage conversions. AHK_L can do this now.
Unicode2Ansi(ByRef wString, ByRef sString, CP = 0)
{
nSize := DllCall("WideCharToMultiByte" , "Uint", CP, "Uint", 0 , "UintP", wString , "int", -1 , "Uint", 0 , "int", 0 , "Uint", 0 , "Uint", 0)
VarSetCapacity(sString, nSize)
DllCall("WideCharToMultiByte" , "Uint", CP , "Uint", 0 , "UintP", wString , "int", -1 , "str", sString , "int", nSize , "Uint", 0 , "Uint", 0)
}
;Old function for codepage conversions. AHK_L can do this now.
Ansi2Unicode(ByRef sString, ByRef wString, CP = 0)
{
nSize := DllCall("MultiByteToWideChar" , "Uint", CP , "Uint", 0 , "UintP", sString , "int", -1 , "Uint", 0 , "int", 0)
VarSetCapacity(wString, nSize * 2)
DllCall("MultiByteToWideChar" , "Uint", CP , "Uint", 0 , "UintP", sString , "int", -1 , "UintP", wString , "int", nSize)
}
;Performs a fuzzy search for string2 in string1.
;return values range from 0.0 = identical to 1.0 = completely different. 0.4 seems appropriate
FuzzySearch(longer, shorter, UseFuzzySearch = false)
{
if(longer = shorter)
return 1
lenl := StrLen(longer)
lens := StrLen(shorter)
if(lens > lenl)
return 0
;Check if the shorter string is a substring of the longer string
Contained := InStr(longer, shorter)
if(Contained)
return Contained = 1 ? 1 : 0.8
;Check if string can be matched by omitting characters
if(lens < 5)
{
pos := 0
matched := 0
Loop % lens
{
char := SubStr(shorter, A_Index, 1)
StringUpper, char, char
Loop % lenl - pos
{
if(SubStr(longer, pos + A_Index, 1) == char)
{
pos := A_Index
matched++
break
}
else
continue
}
}
if(matched = lens)
return 0.9 ;Slightly worse than direct matches
}
;Calculate fuzzy string difference
if(UseFuzzySearch)
{
max := 0
Loop % lenl - lens + 1
{
distance := 1 - StringDifference(shorter, SubStr(longer, A_Index, lens))
if(distance < max)
max := distance
}
return max
}
return 0
}
;By Toralf:
;basic idea for SIFT3 code by Siderite Zackwehdex
;http://siderite.blogspot.com/2007/04/super-fast-and-accurate-string-distance.html
;took idea to normalize it to longest string from Brad Wood
;http://www.bradwood.com/string_compare/
;Own work:
; - when character only differ in case, LSC is a 0.8 match for this character
; - modified code for speed, might lead to different results compared to original code
; - optimized for speed (30% faster then original SIFT3 and 13.3 times faster than basic Levenshtein distance)
;http://www.autohotkey.com/forum/topic59407.html
StringDifference(string1, string2, maxOffset=3) { ;returns a float: between "0.0 = identical" and "1.0 = nothing in common"
If (string1 = string2)
Return (string1 == string2 ? 0/1 : 0.2/StrLen(string1)) ;either identical or (assumption:) "only one" char with different case
If (string1 = "" OR string2 = "")
Return (string1 = string2 ? 0/1 : 1/1)
StringSplit, n, string1
StringSplit, m, string2
ni := 1, mi := 1, lcs := 0
While((ni <= n0) AND (mi <= m0)) {
If (n%ni% == m%mi%)
EnvAdd, lcs, 1
Else If (n%ni% = m%mi%)
EnvAdd, lcs, 0.8
Else{
Loop, %maxOffset% {
oi := ni + A_Index, pi := mi + A_Index
If ((n%oi% = m%mi%) AND (oi <= n0)){
ni := oi, lcs += (n%oi% == m%mi% ? 1 : 0.8)
Break
}
If ((n%ni% = m%pi%) AND (pi <= m0)){
mi := pi, lcs += (n%ni% == m%pi% ? 1 : 0.8)
Break
}
}
}
EnvAdd, ni, 1
EnvAdd, mi, 1
}
Return ((n0 + m0)/2 - lcs) / (n0 > m0 ? n0 : m0)
}
;Returns true if the string is in URL format. Use CouldBeURL() for weaker checks.
IsURL(string)
{
return RegexMatch(strTrim(string, " "), "(?:(?:ht|f)tps?://|www\.).+\..+") > 0
}
;Returns true if the string could be a URL. Use IsURL() to be sure.
CouldBeURL(string)
{
return RegexMatch(strTrim(string, " "), "(?:(?:ht|f)tps?://|www\.)?.+\..+") > 0
}
;Tests for write access to a specific file
WriteAccess( F ) {
if(FileExist(F))
Return ((h := DllCall("_lopen", AStr, F, Int, 1, "Ptr")) > 0 ? 1 : 0) (DllCall("_lclose", "Ptr", h) + NULL)
else
{
SplitPath, F,,Dir
F := FindFreeFilename(Dir)
FileAppend, x, %F%
Success := !ErrorLevel
FileDelete, %F%
return !ErrorLevel
}
}
;Generates MD5 value of a file
FileMD5(sFile´= "", cSz = 4 )
{ ; www.autohotkey.com/forum/viewtopic.php?p=275910#275910
cSz := (cSz < 0 || cSz > 8) ? 2 ** 22 : 2 ** (18 + cSz)
VarSetCapacity(Buffer, cSz, 0)
hFil := DllCall("CreateFile", Str, sFile, UInt, 0x80000000, Int, 1, Int, 0, Int, 3, Int, 0, Int, 0, "Ptr")
if(hFil < 1)
return hFil
DllCall("GetFileSizeEx", Ptr, hFil, Ptr, &Buffer)
fSz := NumGet(Buffer, 0, "Int64")
VarSetCapacity(MD5_CTX, 104, 0)
DllCall("advapi32\MD5Init", PTR, &MD5_CTX)
Loop % (fSz // cSz + !!Mod(fSz, cSz))
DllCall("ReadFile", PTR, hFil, PTR, &Buffer, UInt, cSz, UIntP, bytesRead, UInt, 0)
DllCall("advapi32\MD5Update", PTR, &MD5_CTX, PTR, &Buffer, UInt,bytesRead)
DllCall("advapi32\MD5Final", PTR, &MD5_CTX )
DllCall("CloseHandle", PTR, hFil)
Loop % StrLen(Hex := "123456789ABCDEF0")
{
N := NumGet(MD5_CTX, 87 + A_Index, "Char")