; ------------------------------------------------------------ ; ; _WindowsHotkeys.ahkv2, by Cavalol ; | ; |--> Effective Hotkeys for Windows-based Workstaitons ; | ; |--> Runs via "Autohotkey" (AHK) >> VERSION 2.0-a077-c2bb552 << - Download @ [ https://www.autohotkey.com/download/2.0/AutoHotkey_2.0-a077-c2bb552.zip ] ; | ; |--> Download this script @ [ https://raw.githubusercontent.com/mcavallo-git/Coding/master/ahk/_WindowsHotkeys.ahkv2 ] ; ; ------------------------------------------------------------ ; ; Global Variables - User-Defined ; ; DebugMode := 1 DebugMode := 0 ; ------------------------------------------------------------ ; ; AHK - #Commands (Runtime-Configs) ; https://lexikos.github.io/v2/docs/commands/#hash ; #Persistent ; https://lexikos.github.io/v2/docs/commands/_Persistent.htm #HotkeyInterval 2000 ; https://lexikos.github.io/v2/docs/commands/_HotkeyInterval.htm #MaxHotkeysPerInterval 2000 ; https://lexikos.github.io/v2/docs/commands/_MaxHotkeysPerInterval.htm #SingleInstance Force ; https://lexikos.github.io/v2/docs/commands/_SingleInstance.htm DetectHiddenWindows 1 ; https://lexikos.github.io/v2/docs/commands/DetectHiddenWindows.htm ; DetectHiddenText 1 ; https://lexikos.github.io/v2/docs/commands/DetectHiddenText.htm ; #InstallKeybdHook ; https://lexikos.github.io/v2/docs/commands/_InstallKeybdHook.htm ; #UseHook True ; https://lexikos.github.io/v2/docs/commands/_UseHook.htm SetWorkingDir %A_ScriptDir% ; https://lexikos.github.io/v2/docs/commands/SetWorkingDir.htm SetCapsLockState Off ; https://lexikos.github.io/v2/docs/commands/SetNumScrollCapsLockState.htm ; FileEncoding, UTF-8 ; https://lexikos.github.io/v2/docs/commands/FileEncoding.htm ; #ErrorStdOut ; https://lexikos.github.io/v2/docs/commands/_ErrorStdOut.htm ; ------------------------------------------------------------ ; ; Global Variables - Standardized / Statics ; ; ; Newline Characters ; CR := "`r" LF := "`n" ; ; RFC3339-Specific Variables ( Internet date-time/timestamp standardization values, https://tools.ietf.org/html/rfc3339 ) ; | ; |--> Example - RFC-3339 timestamp w/ timezone: "2020-07-25 05:46:03-05:00" ; RFC3339_YearMonthDay_Separator := "-" ; Character-separator between [ year, month, and day date-field values ] RFC3339_HourMinuteSecond_Separator := ":" ; Character-separator between [ hour, minute, and second time-field ] values RFC3339_DecimalSeconds_Separator := "." ; Character-separator between [ seconds and fractions-of-a-second (microsecond/millisecond) values ] RFC3339_DateAndTimeField_Separator := "T" ; Character-separator between [ date- and time-fields ] RFC3339_UTC_ZeroHourReplacement := "Z" ; Replacement-string to use for timezone when the UTC timezone (UTC+00:00) is output ; ------------------------------------------------------------ ; ; Setup targeting [ Windows Explorer ]-classed windows ; GroupAdd, Explorer, ahk_class ExploreWClass ; Unused on Vista and later GroupAdd, Explorer, ahk_class CabinetWClass ; ------------------------------------------------------------ ; ; Show the Version of AHK currently being used to compile this code ; If (DebugMode == 1) { TrayTip, AHK, % ( "Version:" "`n" A_AhkVersion ) ; Toast Notification } ; ------------------------------------------------------------ ; ; Tray-Icon - Use a custom one instead of default AHK Icon (in Notification area next to clock, bottom-right) ; TrayIcon_Cached := "_WindowsHotkeys.cached.ico" TrayIcon_Default := "_WindowsHotkeys.ico" TrayIcon_Gray := "_WindowsHotkeys.gray.ico" If (FileExist(TrayIcon_Default)) { Menu("Tray","Icon",TrayIcon_Default) } ; ------------------------------------------------------------ ; ------------------------------------------------------------ ; --- HOTKEY-LISTENERS --- ; ------------------------------------------------------------ ; ------------------------------------------------------------ ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + Esc ; ACTION: Refresh This Script ::: Closes then re-opens this script (Allows saved changes to THIS script (file) to be tested/applied on the fly) ; ; #Escape:: ~#Escape:: BlockInPut, Off ; Stop blocking input (e.g. restore full interaction) Reload ; Reload this script Sleep 1000 ; If successful, the reload will close this instance during the Sleep, so the line below will never be reached. MsgBox, 4,, The script could not be reloaded. Would you like to open it for editing? ; IfMsgBox, Yes, Edit If (A_MsgBoxResult = "Yes") { Edit } Return ; ------------------------------------------------------------ ; ; HOTKEY: ??? ; ACTION: Attempt to re-run the current program with escalated/elevated privileges (e.g. rerun the current program as admin) ; ; ???:: ; (PSEUDO-CODE) CHECK IF WINDOW IS ALREADY RUNNING AS ADMIN -> IF YES, DO NOTHING ; ;;; ; (PSEUDO-CODE) GET ACTIVE WINDOW'S EXE-PATH ; ;;; ; (PSEUDO-CODE) GET ACTIVE WINDOW'S ADDITIONAL-ARGS ; ;;; ; (PSEUDO-CODE) OPEN WINDOW AS ADMIN ; ;;; ; Return ; ------------------------------------------------------------ ; ; HOTKEY: Apps-Key ; ACTION: Replace functionality with that of the right WinKey by using a "pass-through" (~) hotkey --> https://www.autohotkey.com/docs/HotkeyFeatures.htm#pass-through ; AppsKey::RWin ; ------------------------------------------------------------ ; ; HOTKEY: Scroll Lock / Scroll-Lock / ScrollLock ; ACTION: Replace functionality with combo keypress [ Alt + Shift + F10 ] (set in GeForce Experience to hotkey "Toggle Instant Replay On/Off" (under "In-Game Overlay" > "Settings" (cog) > "Keyboard shortcuts")) ; ScrollLock:: ; Send ^!+Z Send !+{F10} Return ; ------------------------------------------------------------ ; ; HOTKEY: Pause/Break ; ACTION: Replace functionality with combo keypress [ Alt + F10 ] (set in GeForce Experience to hotkey "Save the last 1.0 minutes recorded" (under "In-Game Overlay" > "Settings" (cog) > "Keyboard shortcuts")) ; Pause:: Send !{F10} TrayTip, AHK, % ( "Recording Saved`nPress [ Shift+Pause/Break ] to view in output directory explorer" ) ; Toast Notification Return ; ------------------------------------------------------------ ; ; HOTKEY: Shift + Pause/Break ; ACTION: Open the current user's Videos directory ; +Pause:: Fullpath_OpenInExplorer := ( EnvGet("USERPROFILE") "\Videos" ) TrayTip, AHK, % ( "Opening Directory [ " Fullpath_OpenInExplorer " ]" ) ; Toast Notification Run "%Fullpath_OpenInExplorer%" ; Open the directory Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + Z ; ACTION: Grabs information about current (active) window's exe-filepath, process-id, on-screen location, & more, and displays it in a popup table Gui ; #z:: GetWindowSpecs() Return ; ------------------------------------------------------------ ; ; APP-SPECIFIC HOTKEY(S): Foxit PhantomPDF ; #If WinActive("ahk_exe FoxitPhantomPDF.exe") ; ; HOTKEY: WinKey + A (while [ Foxit PhantomPDF ] is active) ; ACTION: Edit > Add Text ; #a:: Global DebugMode CoordMode, Mouse, Screen SetDefaultMouseSpeed, 0 SetControlDelay, -1 SetTitleMatchMode, 3 ; A window's title must exactly match WinTitle to be a match WinGetTitle, WinTitle, A If (DebugMode == 1) { TrayTip, AHK, % ( "Foxit PhantomPDF:" "`n" "Clicking 'Edit' > 'Add Text'" ) ; Toast Notification } ; Click the "Edit" tab xpos := 223 ypos := 40 ControlClick, x%xpos% y%ypos%, %WinTitle% Sleep 100 ; Click the "Add Text" button xpos := 338 ypos := 87 ControlClick, x%xpos% y%ypos%, %WinTitle% Return ; ; HOTKEY: Ctrl + B (while [ Foxit PhantomPDF ] is active) ; ACTION: Edit > Bold ; ^b:: Global DebugMode CoordMode, Mouse, Screen SetDefaultMouseSpeed, 0 SetControlDelay, -1 SetTitleMatchMode, 3 ; A window's title must exactly match WinTitle to be a match WinGetTitle, WinTitle, A If (DebugMode == 1) { TrayTip, AHK, % ( "Foxit PhantomPDF:" "`n" "Clicking 'Edit' > 'Bold'" ) ; Toast Notification } ; Click the "Edit" tab xpos := 223 ypos := 40 ControlClick, x%xpos% y%ypos%, %WinTitle% Sleep 100 ; Click the "B" (Bold) button xpos := 448 ypos := 106 ControlClick, x%xpos% y%ypos%, %WinTitle% Return ; ; HOTKEY: Ctrl + Y (while [ Foxit PhantomPDF ] is active) ; ACTION: Redo ; ^y:: Global DebugMode ; CoordMode, Mouse, Window SetDefaultMouseSpeed, 0 SetControlDelay, -1 SetTitleMatchMode, 3 ; A window's title must exactly match WinTitle to be a match WinGetTitle, WinTitle, A If (DebugMode == 1) { TrayTip, AHK, % ( "Foxit PhantomPDF:" "`n" "Clicking 'Redo'" ) ; Toast Notification } ; Click the "Redo" button xpos := 187 ypos := 15 Use_ControlClick := 0 If (Use_ControlClick == 1) { ControlClick, x%xpos% y%ypos%, %WinTitle% } Else { MouseGetPos, MouseX, MouseY MouseClick, Left, %xpos%, %ypos% MouseMove, %MouseX%, %MouseY% } Return #If ; ------------------------------------------------------------ ; ; APP-SPECIFIC HOTKEY(S): Cyberpunk 2077 ; #If WinActive("ahk_exe Cyberpunk2077.exe") ; ; HOTKEY: XButton1 (Mouse-Button 4, Mouse 'Back' Side-Button) (while [ Cyberpunk ] is active) ; ACTION: Press [ Escape ] key, instead ; XButton1:: Escape ; ; HOTKEY: XButton2 (Mouse-Button 5, Mouse 'Forward' Side-Button) (while [ Cyberpunk ] is active) ; ACTION: Press [ Left Mouse Click ] key, instead ; XButton2:: Tab ; ; HOTKEY: CapsLock (while [ Cyberpunk ] is active) ; ACTION: Press [ Tab ] key, instead ; CapsLock:: Tab #If !WinActive("ahk_exe Cyberpunk2077.exe") ; ------------------------------------------------------------ ; ; HOTKEY: CapsLock ; ACTION: Permanently DISABLE Capslock (unless the user pressed combo keypress [ Shift + CapsLock ] which toggles CapsLock as-normal) ; CapsLock:: ^CapsLock:: !CapsLock:: #CapsLock:: SetCapsLockState, Off Return +CapsLock:: SetCapsLockState, % GetKeyState("CapsLock", "T") ? "Off" : "On" Return #If ; ------------------------------------------------------------ ; ; APP-SPECIFIC HOTKEY(S): Overwatch ; #If WinActive("ahk_exe Overwatch.exe") ; ; HOTKEY: Numpad-Enter (while [ Overwatch ] is active) ; ACTION: Do nothing, e.g. Ignore numpad-enter-button presses while in-game (prone to being hit by mouse while sweeping) ; NumpadEnter:: Return #If ; ------------------------------------------------------------ ; ; APP-SPECIFIC HOTKEY(S): Destiny 2 ; #If WinActive("ahk_exe destiny2.exe") ; ; HOTKEY: Numpad-Enter (while [ Destiny 2 ] is active) ; ACTION: Do nothing, e.g. Ignore numpad-enter-button presses while in-game (prone to being hit by mouse while sweeping) ; NumpadEnter:: Return #If ; ; ; ; SET ANY EXISTENT GAME-WINDOW ACTIVE UPON JOYSTICK BUTTON-/TRIGGER-PRESS ; ; ; Joy1:: ; Joy2:: ; Joy3:: ; Joy4:: ; Joy5:: ; Joy6:: ; Joy7:: ; Joy8:: ; Joy9:: ; Joy10:: ; Joy11:: ; Joy12:: ; Joy13:: ; Joy14:: ; Joy15:: ; Joy16:: ; Joy17:: ; Joy18:: ; Joy19:: ; Joy20:: ; Joy21:: ; Joy22:: ; Joy23:: ; Joy24:: ; Joy25:: ; Joy26:: ; Joy27:: ; Joy28:: ; Joy29:: ; Joy30:: ; Joy31:: ; Joy32:: ; ; If (DebugMode == 1) { ; Tooltip, % ( "A_ThisHotkey=[" A_ThisHotkey "] "), 100, 100 ; ; } ; Return ; ------------------------------------------------------------ ; ; APP-SPECIFIC HOTKEY(S): Xbox Console Companion ; #If WinExist("Xbox Console Companion") ; ; HOTKEY: WinKey + F3 (or "#SC03D") ; ACTION: Xbox Captures - Download & Delete recordings/captures via XBox's Windows 10 built-in application ; #F3:: XBox_DownloadDelete_GameClips() Return #If ; ------------------------------------------------------------ #If !WinExist("Xbox Console Companion") ; ; HOTKEY: WinKey + F3 ; ACTION: Hover the mouse over a target area to trigger specific browser-based effects (Javascript on-hover, on cursor entry, on cursor exit, etc.) ; #F3:: BrowserHover() Return #If ; ------------------------------------------------------------ ; ; APP-SPECIFIC HOTKEY(S): Youtube ; ; #If WinExist("Youtube") #If WinExist("Channel content - YouTube Studio - Google Chrome") ; ; HOTKEY: WinKey + F4 ; ACTION: Youtube - Walk uploads from "Draft" to live state ; #F4:: Youtube_EditDraft_Submit() Return #If ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + Minus-Key ( - ) ; WinKey + Numpad-Minus-Key ( - ) ; Alt + WinKey + Minus-Key ( - ) ; Alt + WinKey + Numpad-Minus-Key ( - ) ; Ctrl + WinKey + Minus-Key ( - ) ; Ctrl + WinKey + Numpad-Minus-Key ( - ) ; Ctrl + Alt + WinKey + Minus-Key ( - ) ; Ctrl + Alt + WinKey + Numpad-Minus-Key ( - ) ; ACTION: Type a line of dashes ----- (override default windows-hotkey for the magnifier tool) ; #-:: #NumpadSub:: SendDashedLine(60) Return ^#-:: !#-:: !^#-:: ^#NumpadSub:: !#NumpadSub:: !^#NumpadSub:: SendDashedLine(30) Return ; ------------------------------------------------------------ ; ; HOTKEY: Shift + WinKey + Minus-Key ( - ) ; Shift + WinKey + Numpad-Minus-Key ( - ) ; Shift + Alt + WinKey + Minus-Key ( - ) ; Shift + Alt + WinKey + Numpad-Minus-Key ( - ) ; Shift + Ctrl + WinKey + Minus-Key ( - ) ; Shift + Ctrl + WinKey + Numpad-Minus-Key ( - ) ; Shift + Ctrl + Alt + WinKey + Minus-Key ( - ) ; Shift + Ctrl + Alt + WinKey + Numpad-Minus-Key ( - ) ; ACTION: Type a line of underscores _____ ; +#-:: +#NumpadSub:: SendUnderscoreLine(60) Return +^#-:: +!#-:: +!^#-:: +^#NumpadSub:: +!#NumpadSub:: +!^#NumpadSub:: SendUnderscoreLine(30) Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + Equals-Key ( = ) ; WinKey + Plus-Key ( + ) ; ACTION: Create a citations footer (refer to function description for more info) ; #=:: #+:: #NumpadAdd:: CreateCitationsFooter() Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + V ; ACTION: Open VS Code ; #v:: Open_VisualStudioCode() Return ; ------------------------------------------------------------ ; ; HOTKEY: Ctrl + Shift + V ; HOTKEY: Ctrl + Alt + V ; HOTKEY: Ctrl + WinKey + V ; ACTION: Paste the Clipboard ; *+^v:: *^!v:: *^#v:: PasteClipboardAsBinary() Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + P ; ACTION: Send a random string ; #p:: AwaitModifierKeyup() SendPseudoRandomString() ; SendRandomString(18, 1, 1, 0, 0, 1, 0) Return ; ------------------------------------------------------------ ; ; HOTKEY: Ctrl + WinKey + P ; HOTKEY: Shift + Alt + P ; HOTKEY: Shift + Ctrl + P ; HOTKEY: Shift + WinKey + P ; ACTION: Ask user if they wish to paste the clipboard as Text or Binary data (workaround for websites which block pasting into forms) ; ^#p:: +#p:: +!p:: +^p:: AwaitModifierKeyup() ; Wait until all modifier keys are released PasteClipboard_TextOrBinary() Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + H ; ACTION: Type the COMPUTERNAME ; #h:: SendHostname() Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + U ; ACTION: Type the DOMAIN-USERNAME ; #u:: SetKeyDelay, 0, -1 AwaitModifierKeyup() ; Wait until all modifier keys are released Object_WMI_Service := ComObjGet("winmgmts:{impersonationLevel=impersonate}!\\" A_ComputerName "\root\cimv2") For objComputer in Object_WMI_Service.ExecQuery("Select * from Win32_ComputerSystem") { Domain := objComputer.Domain, Workgroup := objComputer.Workgroup } USERDOMAIN := EnvGet("USERDOMAIN") RET_VAL := A_UserName "@" Domain "_via_" USERDOMAIN Send %RET_VAL% Return ; ------------------------------------------------------------ ; ; HOTKEY: Alt + Z ; ACTION: If VSCode is active, enable Text Wrap in it - Otherwise, bring up the GeForce Experience Overlay (must manually set hotkey in said overlay to match +!z) ; #UseHook False ; Disable the catching of hotkeys sent by this script (stops infinite loops) | https://lexikos.github.io/v2/docs/commands/_UseHook.htm !z:: SetKeyDelay, 0, -1 SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring AwaitModifierKeyup() ; Wait until all modifier keys are released WinTitle := " - Visual Studio Code" If (WinActive(WinTitle)) { Send !z ; Win_ahk_id := WinGetID("A") ; Win_ahk_pid := WinGetPID("ahk_id %Win_ahk_id%") ; ControlSend,, !z, ahk_pid %Win_ahk_pid% ; ControlSend,, {LAlt up}{RAlt up}{LAlt down}{z}{LAlt up}, "ahk_pid %Win_ahk_pid%" } Else { ; Send [ Shift + Alt + z ] - Configure this in Geforce Experience Overlay via "⚙️" > "Keyboard shortcuts" > "Open/close in-game overlay" (set this hotkey) Send +!z } Return #UseHook True ; Enable the catching of hotkeys sent by this script | https://lexikos.github.io/v2/docs/commands/_UseHook.htm ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + G ; HOTKEY: WinKey + W ; ACTION: Types the contents of target file - Optionally, only perform the paste if the currently active window's executable filepath matches a predefined 'whitelisted' exe-filepath ; #g:: #w:: KeysPressed := A_ThisHotkey FileToPaste_Legend := EnvGet("USERPROFILE") "\.ahk\" KeysPressed ExeToRequire_Legend := FileToPaste_Legend "-exe" FileToPaste_Contents := "" ExeToRequire_Fullpath := "" DoPaste := 0 If (FileExist(FileToPaste_Legend)) { If (FileExist(ExeToRequire_Legend)) { ; Get required/whitelisted exe fullpath to match active against FileRead, ExeToRequire_Fullpath, %ExeToRequire_Legend% Win_fullpath := WinGetProcessPath("A") If ((ExeToRequire_Fullpath != "") && (ExeToRequire_Fullpath == Win_fullpath)) { ; Exe path-matching succeeded DoPaste := 1 If (DebugMode == 1) { TrayTip, AHK, % ( "Info - Allowing paste" "`n" "Win_fullpath == '" ExeToRequire_Fullpath "'" ) ; Toast Notification } } Else { ; Exe path-matching failed DoPaste := 0 If (DebugMode == 1) { TrayTip, AHK, % ( "Error (invalid exe) - Blocking paste" "`n" "Win_fullpath != '" ExeToRequire_Fullpath "'" ) ; Toast Notification } Else { ; !! Always show at-least the shortened form of this error !! TrayTip, AHK, % ( "Error (invalid exe) - Blocking paste" ) ; Toast Notification } } } Else { ; Skip matching on the active window's executable fullpath DoPaste := 1 If (DebugMode == 1) { TrayTip, AHK, % ( "Info - Allowing paste" "`n" "!! Skipped exe path-matching (file not found: [" ExeToRequire_Legend "])" ) ; Toast Notification } } } Else { ; Paste file not found DoPaste := 0 If (DebugMode == 1) { TrayTip, AHK, % ( "Error (file not found) - Blocking paste" "`n" "FileToPaste_Legend=[" FileToPaste_Legend "]" ) ; Toast Notification } } If (DoPaste == 1) { ; If the start menu pops up, wait a (half) second then reactivate desired exe's window If (ExeToRequire_Fullpath != "") { AwaitModifierKeyup() ; Wait until all modifier keys are released Sleep 10 SplitPath %ExeToRequire_Fullpath%, ExeToRequire_Basename, ExeToRequire_Dirname, ExeToRequire_Extension, ExeToRequire_BasenameNoExt, ExeToRequire_Drivename WinActivate, ahk_exe %ExeToRequire_Basename% VarSetCapacity(ExeToRequire_Basename,0) VarSetCapacity(ExeToRequire_Dirname,0) VarSetCapacity(ExeToRequire_Extension,0) VarSetCapacity(ExeToRequire_BasenameNoExt,0) VarSetCapacity(ExeToRequire_Drivename,0) ; VarSetStrCapacity(&ExeToRequire_Basename,0) ; https://lexikos.github.io/v2/docs/commands/VarSetStrCapacity.htm ; VarSetStrCapacity(&ExeToRequire_Dirname,0) ; https://lexikos.github.io/v2/docs/commands/VarSetStrCapacity.htm ; VarSetStrCapacity(&ExeToRequire_Extension,0) ; https://lexikos.github.io/v2/docs/commands/VarSetStrCapacity.htm ; VarSetStrCapacity(&ExeToRequire_BasenameNoExt,0) ; https://lexikos.github.io/v2/docs/commands/VarSetStrCapacity.htm ; VarSetStrCapacity(&ExeToRequire_Drivename,0) ; https://lexikos.github.io/v2/docs/commands/VarSetStrCapacity.htm } ; Paste the contents of target file FileRead, FileToPaste_Contents, %FileToPaste_Legend% SendInput, %FileToPaste_Contents% } ; Free variables from memory to avoid caching of secrets or large files - https://www.autohotkey.com/docs/commands/VarSetCapacity.htm VarSetCapacity(FileToPaste_Contents,0) VarSetCapacity(ExeToRequire_Fullpath,0) ; VarSetStrCapacity(&FileToPaste_Contents,0) ; https://lexikos.github.io/v2/docs/commands/VarSetStrCapacity.htm ; VarSetStrCapacity(&ExeToRequire_Fullpath,0) ; https://lexikos.github.io/v2/docs/commands/VarSetStrCapacity.htm Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + D ; ACTION: Types one of a dynamic set of timestamp-strings ; #d:: ; 20200725T080521 (Base Case + WinKey + D) !#d:: ; 20200725T080550-0500 (Alt + WinKey + D) ^#d:: ; 2020-07-25T08:05:55 (Ctrl + WinKey + D) +#d:: ; 20200725T080557.608027 (Shift + WinKey + D) !^#d:: ; 2020-07-25T08:06:04-05:00 (Ctrl + Alt + WinKey + D) +^#d:: ; 2020-07-25T08:06:10.470061 (Shift + Ctrl + WinKey + D) +!#d:: ; 20200725T080613.297487-0500 (Shift + Alt + WinKey + D) +!^#d:: ; 2020-07-25T08:34:12.318040-05:00 (Shift + Ctrl + Alt + WinKey + D) <-- NOTE: For some reason, Microsoft made [ Alt + Ctrl + Shift + WinKey ] open their Win10 Office app --> Disable via https://superuser.com/a/1484507 Global RFC3339_YearMonthDay_Separator Global RFC3339_HourMinuteSecond_Separator Global RFC3339_DecimalSeconds_Separator Global RFC3339_DateAndTimeField_Separator SetKeyDelay, 0, -1 AwaitModifierKeyup() ; Wait until all modifier keys are released YMD_Separator := RFC3339_YearMonthDay_Separator HMS_Separator := RFC3339_HourMinuteSecond_Separator Microseconds_Separator := RFC3339_DecimalSeconds_Separator DT_Field_Separator := RFC3339_DateAndTimeField_Separator Add_Microseconds := 0 Add_Timezone := 0 KeysPressed := A_ThisHotkey If (InStr(KeysPressed, "+") = 1) { ; Shift + [...] Add_Microseconds := 1 KeysPressed := StrReplace(KeysPressed,"+","") } If (InStr(KeysPressed, "!") = 1) { ; Alt + [...] Add_Timezone := 1 KeysPressed := StrReplace(KeysPressed,"!","") } If (DebugMode == 1) { TrayTip, AHK, % ( "A_ThisHotkey=[" A_ThisHotkey "] KeysPressed=[" KeysPressed "] Add_Microseconds=[" Add_Microseconds "] Add_Timezone=[" Add_Timezone "] ") ; Toast Notification } If (KeysPressed = "#D") { ; WinKey + D ; Output a "filename-friendly" timestamp ; |--> Generally-speaking, only allow characters which are alphanumeric "[a-zA-Z0-9]", dashes "-", plus-signs "+", and periods "." YMD_Separator := "" HMS_Separator := "" DT_Field_Separator := RFC3339_DateAndTimeField_Separator } Else If (KeysPressed = "^#D") { ; Ctrl + WinKey + D ; Default to RFC 3339 format } Else { ; Fallthrough ; Default to RFC 3339 format } ; Get the current timestamp Keys := GetTimestamp(YMD_Separator, HMS_Separator, DT_Field_Separator) ; Add [ fractions-of-a-second ] onto output timestamp If (Add_Microseconds = 1) { GetMicroseconds(Current_Microseconds) Keys := Keys Microseconds_Separator Current_Microseconds } ; Add [ Timezone ] onto output timestamp If (Add_Timezone = 1) { Current_TZ := "" GetTimezoneOffset(Current_TZ, HMS_Separator) Keys := Keys Current_TZ } Send(Keys) Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + F1 ; ACTION: Edit this Script (the one you're reading right now) ; #F1:: Run Notepad %A_ScriptFullPath% Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + F2 ; ACTION: Opens a window (GetKeyCodes.ahk) which displays verbose keypress info, live (allowing user to press combo keys and view how it is interpreted by AHK) ; #F2:: GetKeyCodes := A_ScriptDir "\GetKeyCodes.ahk" Run %GetKeyCodes% Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + F8 ; ACTION: Send duplicate keypresses ; #F8:: Duplicate_Keypress() Return ; ------------------------------------------------------------ ; ; HOTKEY: Ctrl + WinKey + Z ; Shift + WinKey + Z ; ACTION: Show all (current) Window Titles ; ^#z:: +#z:: ShowWindowTitles() Return ; ------------------------------------------------------------ ; ; HOTKEY: Alt + WinKey + R ; Ctrl + WinKey + R ; Shift + WinKey + R ; Shift + Alt + R ; Shift + Ctrl + R ; ACTION: Open Windows 10's "Display settings" (to change resolution, monitor settings, etc.) ; !#r:: ^#r:: +#r:: Run % (EnvGet("WINDIR") "\System32\control.exe" " " "desk.cpl") Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + [ ; ACTION: FOLLOW-UP HOTKEY TO: WinKey P ::: Click "Duplicate" monitors ; #[:: AppsKey & [:: #]:: AppsKey & ]:: Global DebugMode CoordMode, Mouse, Screen SetDefaultMouseSpeed, 0 SetControlDelay, -1 SetTitleMatchMode, 1 ; A window's title must start with the specified WinTitle to be a match ; Save current monitor config (to compare against once it's been updated) SysGet, MonitorCountBefore, 80 SysGet, ViewportWidthBefore, 78 SysGet, ViewportHeightBefore, 79 ; Save current mouse coordinates MouseGetPos, MouseX, MouseY ; Send an Escape keypress to close any old Projection menus Send {Escape} Sleep 250 If (A_OSVersion="WIN_7") { ; Windows7 If ((A_ThisHotkey=="#[") || (A_ThisHotkey=="AppsKey & [")) { ; Duplicate Monitors xpos := 874 ypos := 520 } Else If ((A_ThisHotkey=="#]") || (A_ThisHotkey=="AppsKey & ]")) { ; Extend Monitors xpos := 1044 ypos := 520 } Send {LWin up}{RWin up}{LWin down}{p}{LWin up} Sleep 2000 MouseClick, Left, %xpos%, %ypos% Sleep 100 } Else If (SubStr(A_OSVersion, 1, 4)="10.0") { ; Windows10 ; Open the "Projection" window Send {LWin up}{RWin up}{LWin down}{p}{LWin up} Sleep 250 StartMilliseconds := A_TickCount Loop { LoopingForMilliseconds := (A_TickCount-StartMilliseconds) WinTitle := "A" Win_title := WinGetTitle(WinTitle) Win_ahk_class := WinGetClass(WinTitle) Win_ahk_exe := WinGetProcessName(WinTitle) If ((Win_title=="Project") && (Win_ahk_class=="Windows.UI.Core.CoreWindow") && (Win_ahk_exe=="ShellExperienceHost.exe")) { ; Projection menu detected --> select related option (duplicate/extend) Sleep 250 Random, RandomSleep, 1000, 1500 Sleep %RandomSleep% If ((A_ThisHotkey=="#[") || (A_ThisHotkey=="AppsKey & [")) { ; Duplicate Monitors xpos := (A_ScreenWidth - 20) ypos := 210 } Else If ((A_ThisHotkey=="#]") || (A_ThisHotkey=="AppsKey & ]")) { ; Extend Monitors xpos := (A_ScreenWidth - 20) ypos := 315 } ; Select Projection menu option MouseClick, Left, %xpos%, %ypos% ; Wait until the new monitor layout is loaded Loop 30 { Sleep 100 Random, RandomSleep, 1000, 1500 Sleep %RandomSleep% SysGet, MonitorCountAfter, 80 If (MonitorCountAfter != MonitorCountBefore) { Break } } ; Click outside of the Projection menu to close it MouseClick, Left, %MouseX%, %MouseY% Sleep 100 Random, RandomSleep, 1000, 1500 Sleep %RandomSleep% ; Send an Escape keypress to ensure the Projection menu closes Send {Escape} Sleep 100 Random, RandomSleep, 1000, 1500 Sleep %RandomSleep% Break } Else If (LoopingForMilliseconds > 2000) { MsgBox, (LTrim Error: Unable to locate Projection window ) Break } Else { Sleep 10 Random, RandomSleep, 1000, 1500 Sleep %RandomSleep% } } } MouseMove, %MouseX%, %MouseY% If (DebugMode == 1) { SysGet, MonitorCountAfter, 80 SysGet, ViewportWidthAfter, 78 SysGet, ViewportHeightAfter, 79 ; Check-for Windows' percentage (%) based display scaling Get_CurrentVerticalResolution := "PowerShell.exe -Command '([String]((Get-CimInstance -ClassName CIM_VideoController).CurrentVerticalResolution)).Trim();'" CurrentVerticalResolution := GetCommandOutput(Get_CurrentVerticalResolution) CurrentVerticalResolution := StrReplace(StrReplace(StrReplace(CurrentVerticalResolution, "`n", ""), "`v", ""), "`r", "") ; Read the registry to check for display scaling KeyName := "HKEY_CURRENT_USER\Control Panel\Desktop" PropertyName := "DpiScalingVer" RegRead, DpiScalingVer, %KeyName%, %PropertyName% PropertyName := "Win8DpiScaling" RegRead, Win8DpiScaling, %KeyName%, %PropertyName% PropertyName := "DpiScalingVer" RegRead, LogPixels, %KeyName%, %PropertyName% ; ------------------------------------------------------------ ; ; DpiScalingVer ; originally 1000 ; Win8DpiScaling ; originally 0 ; LogPixels ; originally absent ; ; DPI--->Scale Factor ; 96 === x60 <-- 100% ; 120 === x78 <-- 125% ; 144 === x90 <-- 150% ; 192 === xC0 <-- 200% ; 240 === xF0 <-- 250% ; ; From: https://www.tenforums.com/general-support/69742-resolution-mismatch-when-using-change-size-text.html#post869493 ; ; ------------------------------------------------------------ ; HKEY_CURRENT_CONFIG\System\CurrentControlSet\Control\Video ; ; DefaultSetting.XResolution ; REG_DWORD ; 0x00000400 (1024) ; ; DefaultSetting.YResolution ; REG_DWORD ; 0x00000300 (768) ; ; From: https://superuser.com/a/1050763 ; ; ------------------------------------------------------------ MsgBox, (LTrim xpos = %xpos% ypos = %ypos% ViewportWidthBefore = %ViewportWidthBefore% ViewportWidthAfter = %ViewportWidthAfter% ViewportHeightBefore = %ViewportHeightBefore% ViewportHeightAfter = %ViewportHeightAfter% DpiScalingVer = %DpiScalingVer% Win8DpiScaling = %Win8DpiScaling% LogPixels = %LogPixels% ) } Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + Right-Click ; ACTION: Follows the mouse-cursor and displays its the X,Y coordinates (as a tooltip next to the cursor) ; #RButton:: FollowDuration_Seconds := 20 ; ShowCursorCoordinates(FollowDuration_Seconds) ShowCursorPixelColor(FollowDuration_Seconds) Return ; ------------------------------------------------------------ ; ; HOTKEY: Shift + WinKey + Right-Click ; Ctrl + WinKey + Right-Click ; Alt + WinKey + Right-Click ; ACTION: Follows the mouse-cursor and displays the color of the pixel under it, continuously (as a tooltip next to the cursor) ; +#RButton:: !#RButton:: ^#RButton:: FollowDuration_Seconds := 20 ; ShowCursorCoordinates(FollowDuration_Seconds) ShowCursorPixelColor(FollowDuration_Seconds) Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + L ; ACTION: Allow native function (via ~) to lock the workstatiton, wait a sec, then show the screensaver ; #l:: AppsKey & l:: LockWorkstation() ; Monitor_ShowScreenSaver() Reload Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + N ; ACTION: Opens "View Network Connections" (control panel window) ; #n:: Open_ControlPanel_NetworkConnections() Return ; ------------------------------------------------------------ ; HOTKEY: WinKey + S ; ACTION: Opens "Sound" > "Playback" (control panel window) ; #s:: Open_ControlPanel_Sound("Playback") ; Open_ControlPanel_Sound("Recording") Return ; ------------------------------------------------------------ ; HOTKEY: Alt + WinKey + S ; Ctrl + WinKey + S ; Shift + WinKey + S ; ACTION: Opens "Sound" > "Recording" (control panel window) ; !#s:: ^#s:: +#s:: Open_ControlPanel_Sound("Recording") Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + O (not zero, the letter O) ; ACTION: Opens "Programs & Features" in the Control Panel ; #o:: Run "c:\windows\system32\appwiz.cpl" Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + E ; ACTION: Opens directory pointed to by Windows' USERPROFILE environment variable ; #e:: Run % EnvGet("USERPROFILE") Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + ` (Tilde) ; ACTION: Keyboard-Command for a Mouse-Left-Click ; #`:: MouseClick, Left Return ; ------------------------------------------------------------ ; ; HOTKEY: AppsKey + Mouse-Wheel Up ; AppsKey + Mouse-Wheel Down ; ACTION: Simulate a Mouse Left-Click (instead of scrolling up/down) ; ; AppsKey & WheelUp:: ; AppsKey & WheelDown:: ; CoordMode, Mouse, Screen ; SetDefaultMouseSpeed, 0 ; MouseGetPos, MouseX, MouseY ; MouseClick, Left, %MouseX%, %MouseY% ; Sleep 10 ; Return ; ------------------------------------------------------------ ; ; HOTKEY: AppsKey + Left/Right/Up/Down ; ACTION: Replace AppsKey with RWin and send command ; AppsKey & Left:: Send {LWin up}{RWin up}{LWin down}{Left}{LWin up} Return AppsKey & Right:: Send {LWin up}{RWin up}{LWin down}{Right}{LWin up} Return AppsKey & Up:: Send {LWin up}{RWin up}{LWin down}{Up}{LWin up} Return AppsKey & Down:: Send {LWin up}{RWin up}{LWin down}{Down}{LWin up} Return ; ------------------------------------------------------------ ; ; HOTKEY: Alt + ` (Tilde) ; ACTION: Keyboard-Command for a Mouse-Right-Click ; !`:: MouseClick, Right Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey/AppsKey + XButton1 (Mouse-Button 4, Mouse 'Back' Side-Button) ; ACTION: Goto Previous Track (in currently-active media player) ; #XButton1:: AppsKey & XButton1:: Send {Media_Prev} Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey/AppsKey + XButton2 (Mouse-Button 5, Mouse 'Front' Side-Button) ; ACTION: Goto Next Track (in currently-active media player) ; #XButton2:: AppsKey & XButton2:: Send {Media_Next} Return ; ------------------------------------------------------------ ; ; ; 3-Key Hotkeys (Using AppsKey, LWin, or RWin) ; #If GetKeyState("LWin", "P") || GetKeyState("RWin", "P") || GetKeyState("AppsKey", "P") ; ; ACTION: Volume Up ; Alt & Up:: Ctrl & Up:: Shift & Up:: VolDelta := 2 SoundSet , % ( "+" VolDelta ) ShowVolumeLevel() Return ; ; ACTION: Volume Down ; Alt & Down:: Ctrl & Down:: Shift & Down:: VolDelta := 2 SoundSet , % ( "-" VolDelta ) ShowVolumeLevel() Return ; ; ACTION: Goto previous track (in active media player) ; Ctrl & Left:: Shift & Left:: Send {Media_Prev} Return ; ; ACTION: Goto next track (in active media player) ; Ctrl & Right:: Shift & Right:: Send {Media_Next} Return ; ; ACTION: Decrease screen brightness ; Alt & Left:: BS := new BrightnessSetter() BS.SetBrightness(-1) Return ; ; ACTION: Increase screen brightness ; Alt & Right:: BS := new BrightnessSetter() BS.SetBrightness(+1) Return ; ; ACTION: Pause current track (in active media player) ; Alt & Space:: Ctrl & Space:: Shift & Space:: Send {Media_Play_Pause} Return #If #F10:: #F11:: #F12:: #MButton:: #WheelUp:: #WheelDown:: ^#MButton:: ^#WheelUp:: ^#WheelDown:: AppsKey & WheelUp:: AppsKey & WheelDown:: VolDelta := 2 If (A_ThisHotkey=="#F10") { SoundSet, +1, , MUTE ; Volume Mute (Toggle) } Else If (A_ThisHotkey=="#MButton") { SoundSet, +1, , MUTE ; Volume Mute (Toggle) } Else If (A_ThisHotkey=="^#MButton") { SoundSet, +1, , MUTE ; Volume Mute (Toggle) } Else { If (A_ThisHotkey=="#F12") { vDelta := "+" ( VolDelta ) ; Volume Up } Else If (A_ThisHotkey=="+#Up") { vDelta := "+" ( VolDelta ) ; Volume Up } Else If (A_ThisHotkey=="!#Up") { vDelta := "+" ( VolDelta ) ; Volume Up } Else If (A_ThisHotkey=="^#Up") { vDelta := "+" ( VolDelta ) ; Volume Up } Else If (A_ThisHotkey=="AppsKey & WheelUp") { vDelta := "+" ( VolDelta ) ; Volume Up } Else If (A_ThisHotkey=="#WheelUp") { vDelta := "+" ( VolDelta ) ; Volume Up } Else If (A_ThisHotkey=="^#WheelUp") { vDelta := "+" ( VolDelta * 2 ) ; Volume Up x2 } Else If (A_ThisHotkey=="+#Down") { vDelta := "-" ( VolDelta ) ; Volume Down } Else If (A_ThisHotkey=="#F11") { vDelta := "-" ( VolDelta ) ; Volume Down } Else If (A_ThisHotkey=="!#Down") { vDelta := "-" ( VolDelta ) ; Volume Down } Else If (A_ThisHotkey=="^#Down") { vDelta := "-" ( VolDelta ) ; Volume Down } Else If (A_ThisHotkey=="AppsKey & WheelDown") { vDelta := "-" ( VolDelta ) ; Volume Down } Else If (A_ThisHotkey=="#WheelDown") { vDelta := "-" ( VolDelta ) ; Volume Down } Else If (A_ThisHotkey=="^#WheelDown") { vDelta := "-" ( VolDelta * 2 ) ; Volume Down x2 } SoundSet , %vDelta% } ShowVolumeLevel() Return ; ------------------------------------------------------------ ; ; HOTKEY: Alt + Mouse-Wheel Up/Down ; ACTION: "SuperScroll" - scrolls 15 wheel-clicks at a time ; !WheelUp:: MouseClick,WheelUp,,,15,0,D,R Return !WheelDown:: MouseClick,WheelDown,,,15,0,D,R Return ; ------------------------------------------------------------ ; ; HOTKEY: Mouse-Wheel Left-/Right-Tilt (e.g. "Rock" the Mouse-Wheel Left/Right) ; ACTION: Change Tabs Left or Right ; WheelLeft:: Send ^{PgUp} Return WheelRight:: Send ^{PgDn} Return ; ------------------------------------------------------------ ; ; HOTKEY: Ctrl + WinKey + K ; Ctrl + Alt + K ; Ctrl + Shift + K ; Right-WinKey + K ; ACTION: Send a Checkmark ; +^k:: ^!k:: ^#k:: >#k:: SetKeyDelay, 0, -1 ; Send 🗸 ; Light Check Mark ; Send ✔ ; Heavy Check Mark Send ✔️ ; Heavy Check Mark (Colored) Return ; ------------------------------------------------------------ ; ; HOTKEY: Ctrl + WinKey + X ; Ctrl + Alt + X ; Ctrl + Shift + X ; ACTION: Send a Red X ("Cross Mark") ; ^!x:: ^#x:: SetKeyDelay, 0, -1 ; Send ✕ ; Multiplication X ; Send ✖ ; Heavy Multiplication X ; Send ✘ ; Heavy Ballot X Send ❌️ ; Cross Mark Return ; ------------------------------------------------------------ ; ; HOTKEY: Left-WinKey + K ; ACTION: Send a Thumbs-Up ; <#k:: SetKeyDelay, 0, -1 Send 👍 ; Thumbs Up ; Send 👍🏿 ; Thumbs Up: Dark Skin Tone ; Send 👍🏾 ; Thumbs Up: Medium-Dark Skin Tone ; Send 👍🏽 ; Thumbs Up: Medium Skin Tone ; Send 👍🏼 ; Thumbs Up: Medium-Light Skin Tone ; Send 👍🏻 ; Thumbs Up: Light Skin Tone Return ; ------------------------------------------------------------ #If !WinActive("Minecraft") && !WinActive("ahk_exe Cyberpunk2077.exe") && !WinActive("ahk_exe Overwatch.exe") && !WinActive("ahk_exe HaloInfinite.exe") ; ; HOTKEY: WinKey + C ; ACTION: Open Google Chrome ; #c:: Open_Chrome() Return ; #If WinActive("ahk_exe HaloInfinite.exe") ; ; ; ; HOTKEY: Left Mouse-Click ; ; ACTION: Halo Infinite - Send XButton1 (Mouse-Button 4, Mouse 'Back' Side-Button - Bind button as "Mark" hotkey) ; ; ; LButton:: ; Send, {XButton1} ; ; If you click 15 times too quickly, it gives you a 30 second timeout for marking too frequently, so set a timeout after each click ; Sleep 2000 ; Return #If WinActive("ahk_exe Overwatch.exe") ; ; HOTKEY: WinKey + C ; ACTION: Click rapidly ; #c:: ClickLoop(731,1227,25) Return #If WinActive("ahk_exe Cyberpunk2077.exe") ; ; HOTKEY: WinKey + C ; ACTION: Cyberpunk - Farm Athletics EXP ; #c:: Loop { WinActivate Cyberpunk Send {Space} ; Jump Spam ; MouseClick, Left ; Attack Spam Sleep 10 } Return #If WinActive("Minecraft") ; ; HOTKEY: WinKey + C ; ACTION: Minecraft - do various actions ; #c:: SetTitleMatchMode, 1 ; A window's title must start with the specified WinTitle to be a match AwaitModifierKeyup() ; Wait until all modifier keys are released WinTitle := "Minecraft" Max_LoopDuration_Seconds := 7200 Milliseconds_BetweenClicks := 750 Do_SwordAttackSpam := 1 ; Do_SwordAttackSpam := 0 If (Do_SwordAttackSpam == 0) { ; Minecraft - Spam right click (for placing piston to blow through bedrock) Loop 500 { Sleep 10 MouseClick, Right } } Else { ; Minecraft - Sword attack spam TickCount_BeforeLoop := A_TickCount Loop { Loop_HasBeenRunningFor_Seconds := Round(((A_TickCount-TickCount_BeforeLoop)/1000), 2) If ( Loop_HasBeenRunningFor_Seconds > Max_LoopDuration_Seconds) { ; Wait a minimum short-duration per download Tooltip, % "Loop exceeded maximum runtime of [ " Max_LoopDuration_Seconds " ] seconds (current value: [ " Loop_HasBeenRunningFor_Seconds " ] seconds)" Break } Else { If (WinActive(WinTitle)) { Tooltip, % "Loop has been running for [ " Loop_HasBeenRunningFor_Seconds " ] seconds" MouseClick, Left Sleep %Milliseconds_BetweenClicks% } Else { Tooltip, % "Stopped Minecraft auto-clicker (MC window lost focus" Break } } } ClearTooltip(5000) } Return #If ; ------------------------------------------------------------ ; ; HOTKEY: Alt + WinKey + C ; Ctrl + WinKey + C ; ACTION: Workbench hotkey for quick-testing, one-time wizbangs, etc. ; !#c:: ^#c:: ; WinTitle=Task Scheduler ; WinTitle=Visual Studio Code ; SpaceUp_Loop(50, WinTitle) ; SpaceUp_Loop(50) ; ClickLoop(1724,749,1000) MouseGetPos, MouseX, MouseY ClickLoop(MouseX, MouseY, 500) ; ClickLoop(MouseX,MouseY,Timeout) Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + F ; ACTION: Do nothing (kills Windows "Feedback Hub", in the very least) ; #f:: If (1 == 0) { ; ------------------------------------------------------------ ; OLD RUNTIME - Open "Effective File Search" (software) ; ------------------------------------------------------------ ; ExeFilepath := "C:`\Program Files (x86)`\efs`\search.exe" efs := "\Effective File Search.efsp" ; iso=C:\ISO ExeFilepath := "C:`\ISO`\Effective File Search.efsp" ExeFilepath2 := % EnvGet("USERPROFILE") efs ; MsgBox, % ExeFilepath2 If (FileExist(ExeFilepath)) { Run, %ExeFilepath% } Else { If (FileExist(ExeFilepath2)) { Run, %ExeFilepath2% } Else { ; If EFS does NOT exist, offer user the URL to download it exe_download_url := "http://www.sowsoft.com/download/efsearch.zip" MsgBox, 4, Download EFS?, Effective File Search not found`n`nDownload EFS Now? If (A_MsgBoxResult = "Yes") { Run, chrome.exe %exe_download_url% } } } } Return ; ------------------------------------------------------------ ; ; HOTKEY: Left-Shift + Right-Shift (Shift + Shift --> Both Shift-Keys pressed simultaneously) ; ACTION: Toggle between "Maximized" and "Restored" window-sizes for the currently-active window ; ; VKA0 & VKA1:: ;VKA1 = RShift ; VKA1 & VKA0:: ;VKA0 = LShift ; SC02A & SC136:: ;SC136 = RShift ; SC136 & SC02a:: ;SC02A = LShift ; >+LShift:: ;>+ = RShift (Modifier) ; <+RShift:: ;<+ = LShift (Modifier) RShift & LShift:: LShift & RShift:: Win_ToggleRestoreMaximize() Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + 8 ; ACTION: Wait a random duration of time (example) ; #8:: Random, RandomSleep_15s_to_20s, 15000, 20000 TrayTip, AHK, % ( "Sleeping for [" RandomSleep_15s_to_20s "] ms" ) ; Toast Notification Sleep %RandomSleep_15s_to_20s% TrayTip, AHK, % ( "Sleep for [" RandomSleep_15s_to_20s "] ms has finished" ) ; Toast Notification Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + 9 ; ACTION: Send a {PrintScreen} keypress (for keyboards without the printscreen key) ; #9:: AwaitModifierKeyup() ; Wait until all modifier keys are released Send {PrintScreen} Return !#9:: AwaitModifierKeyup() ; Wait until all modifier keys are released Send !{PrintScreen} Return ^#9:: AwaitModifierKeyup() ; Wait until all modifier keys are released Send ^{PrintScreen} Return +#9:: AwaitModifierKeyup() ; Wait until all modifier keys are released Send +{PrintScreen} Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + 0 ; ACTION: Move the currently-active window's top-left corner to the top-left of the screen ; #0:: AwaitModifierKeyup() ; Wait until all modifier keys are released WinMove, A, , 0, 0 Return ; ------------------------------------------------------------ ; Win+J - Start Node.JS (Git-Bash) && Postman ; ; #j:: ; ; - - ; SG_REPO=%USERPROFILE%/Documents/GitHub/supplier_gateway ; ; - - ; POSTMAN_EXE=%LOCALAPPDATA%/Postman/Update.exe ; GIT_BASH_EXE=%PROGRAMFILES%\Git\git-bash.exe ; ; - - ; SG_BUILD_SCRIPT=%SG_REPO%/build/_start_frontend.sh ; SG_BUILD_API_LNK=%SG_REPO%/_start_server_api.lnk ; SG_BUILD_PM_LNK=%SG_REPO%/_start_server_pm.lnk ; SG_BUILD_SG_LNK=%SG_REPO%/_start_server_sg.lnk ; ; - - ; WinTitle_NodeJS=Supplier Gateway (localhost) ; WinTitle_Postman=Postman ; ; - - ; if ((!FileExist(SG_REPO)) || (!InStr(FileExist(SG_REPO), "D"))) { ; MsgBox, ; (LTrim ; Error: Required directory not-found: ; %SG_REPO% ; ) ; } Else { ; ; Microsoft Windows has some unusual values for the window-bounds, when maximized/snapped ; Increment_Left := -7 ; Increment_Top := 0 ; Increment_Width := 14 ; Increment_Height := 7 ; ; Prep Monitor Widths/Heights ; SysGet, DesktopMonitorCount, 80 , N ; BoundsLeft = -1 ; BoundsRight = -1 ; BoundsTop = -1 ; BoundsBottom = -1 ; BoundsCenterHoriz = 0 ; BoundsCenterVert = 0 ; Loop, %DesktopMonitorCount% { ; SysGet, MonitorWorkArea, MonitorWorkArea, %A_Index% ; ; If (%MonitorWorkAreaLeft% > %BoundsLeft%) { ; If (BoundsLeft < MonitorWorkAreaLeft) ; { ; ; MsgBox, Floor(BoundsLeft) < Floor(MonitorWorkAreaLeft) ; ; Widths ; BoundsLeft := MonitorWorkAreaLeft ; BoundsRight := MonitorWorkAreaRight ; ; Heights ; BoundsTop := MonitorWorkAreaTop ; BoundsBottom := MonitorWorkAreaBottom ; } Else { ; ; MsgBox, Floor(BoundsLeft) >= Floor(MonitorWorkAreaLeft) ; } ; } ; ; Widths ; BoundsWidthFull := (BoundsRight - BoundsLeft) ; BoundsWidthHalf := Floor(BoundsWidthFull/2) ; BoundsCenterHoriz := (BoundsLeft + BoundsWidthHalf) ; ; Heights ; BoundsHeightFull := (BoundsBottom - BoundsTop) ; BoundsHeightHalf := Floor(BoundsHeightFull/2) ; BoundsCenterVert := (BoundsTop + BoundsHeightHalf) ; SetTitleMatchMode, 1 ; A window's title must start with the specified WinTitle to be a match ; ; - - ; WinTitle_Postman=Postman ; WinTitle_NodeJS=Supplier Gateway (localhost) ; ; - - ; ; Start Postman ; IfWinNotExist,%WinTitle_Postman% ; { ; ; Need to run the program, as no window was found for it (yet) ; POSTMAN_ARGS= --processStart Postman.exe ; ; POSTMAN_ARGS=--processStart Postman.exe ; Run, %POSTMAN_EXE% %POSTMAN_ARGS% ; } ; ; - - ; Sleep 100 ; ; - - ; ; Start Node.JS in Git-Bash ; IfWinNotExist,%WinTitle_NodeJS% ; { ; GIT_BASH_ARGS_API=-c "C:/Users/%USERNAME%/Documents/GitHub/supplier_gateway/build/_start_frontend.sh rest-api start-localhost;" ; GIT_BASH_ARGS_PM=-c "C:/Users/%USERNAME%/Documents/GitHub/supplier_gateway/build/_start_frontend.sh boneal-app start-localhost;" ; GIT_BASH_ARGS_SG=-c "C:/Users/%USERNAME%/Documents/GitHub/supplier_gateway/build/_start_frontend.sh project-manager start-localhost;" ; Run, %GIT_BASH_EXE% %GIT_BASH_ARGS_API%, %SG_REPO% ; ; Run, %GIT_BASH_EXE% %GIT_BASH_ARGS_PM%, %SG_REPO% ; ; Run, %GIT_BASH_EXE% %GIT_BASH_ARGS_SG%, %SG_REPO% ; } ; ; ; ; Wait until the script(s)/program(s) start before moving them around ; ; WinWait,%WinTitle_Postman%,,5 ; ; WinWait,%WinTitle_NodeJS%,,3 ; ; Move the window to occupy the right-half of the Right-Most monitor ; ; WinMove,%WinTitle_Postman%,,%BoundsCenterHoriz%,%BoundsTop%,%BoundsWidthHalf%,%BoundsHeightFull% ; ; WinMove,%WinTitle_Postman%,,953,0,974,1047 (1st Monitor, Right, Actual) ; ; Move the window to occupy the left-half of the Right-Most monitor ; ; WinMove,%WinTitle_NodeJS%,,%BoundsLeft%,%BoundsTop%,%BoundsWidthHalf%,%BoundsHeightFull% ; ; WinMove,%WinTitle_NodeJS%,,-7,0,974,1047 ;; (1st Monitor, Left, Actual) ; ; ; } ; Return ; ------------------------------------------------------------ ; ; HOTKEY: WinKey + T ; ACTION: Open Windows Terminal ; #t:: Open_WindowsTerminal() Return ; ------------------------------------------------------------ ; ; HOTKEY: Alt + WinKey + T ; Ctrl + WinKey + T ; ACTION: Get Windows Environment Vars ; !#t:: ^#t:: PrintEnv() Return ; ---------------------------------------------------- ; HOTKEY: Num Lock ; ACTION: Keep NumLock state enabled (unless pressed with shift, which enables it) ; Allow for a specific config-file, if exists, to keep NumLock disabled by-default (for specific hardware/VM use-cases) ; NumLock:: ^NumLock:: !NumLock:: #NumLock:: ConfigFilepath_KeepNumLockDisabled := USERPROFILE "\.ahk\numlock-keep-disabled.config" If (!FileExist(ConfigFilepath_KeepNumLockDisabled)) { ; Default - Keep NumLock enabled NumLockEnabled_BeforeKeypress := GetKeyState("NumLock", "T") If (NumLockEnabled_BeforeKeypress == 0) { SetNumLockState, On ; SetNumLockState, % GetKeyState("NumLock", "T") ? "Off" : "On" } Else { TextToolTip := "Disable NumLock via Shift+NumLock" ToolTip, %TextToolTip% ClearTooltip(3000) } } Else { ; Reversed-Default - Keep NumLock disabled (for laptops with a terrible numpad layout (overlaying keys J, L, etc.)) NumLockEnabled_BeforeKeypress := GetKeyState("NumLock", "T") If (NumLockEnabled_BeforeKeypress == 1) { SetNumLockState, Off ; SetNumLockState, % GetKeyState("NumLock", "T") ? "Off" : "On" } Else { TextToolTip := "Enable NumLock via Shift+NumLock" ToolTip, %TextToolTip% ClearTooltip(3000) } } Return +NumLock:: ConfigFilepath_KeepNumLockDisabled := USERPROFILE "\.ahk\numlock-keep-disabled.config" If (!FileExist(ConfigFilepath_KeepNumLockDisabled)) { ; Default - Allow Shift+NumLock to toggle NumLock ; NumLockEnabled_BeforeKeypress := GetKeyState("NumLock", "T") ; If (NumLockEnabled_BeforeKeypress == 1) { ; ; SetNumLockState, Off ; SetNumLockState, % GetKeyState("NumLock", "T") ? "Off" : "On" ; } SetNumLockState, % GetKeyState("NumLock", "T") ? "Off" : "On" } Else { ; Reversed-Default - Only allow Shift+NumLock to enable NumLock (for laptops with a terrible numpad layout (overlaying keys J, L, etc.)) NumLockEnabled_BeforeKeypress := GetKeyState("NumLock", "T") If (NumLockEnabled_BeforeKeypress == 0) { SetNumLockState, On } } Return ; ------------------------------------------------------------ ; ------------------------------------------------------------ ; --- FUNCTIONS --- ; ------------------------------------------------------------ ; ------------------------------------------------------------ ; ; ActiveWindow_Maximize ; |--> Maximize active window (if not maximized, already) ; ActiveWindow_Maximize() { Win_MinMaxState := WinGetMinMax("A") If (Win_MinMaxState<=0) { ; Window is not maximized - maximize it WinMaximize "A" } Return } ; ; AwaitModifierKeyup ; |--> Wait until all modifier keys are released ; AwaitModifierKeyup() { KeyWait LAlt ; Wait for [ Left-Alt ] to be released KeyWait LCtrl ; Wait for [ Left-Control ] to be released KeyWait LShift ; Wait for [ Left-Shift ] to be released KeyWait LWin ; Wait for [ Left-Win ] to be released KeyWait RAlt ; Wait for [ Right-Alt ] to be released KeyWait RCtrl ; Wait for [ Right-Control ] to be released KeyWait RShift ; Wait for [ Right-Shift ] to be released KeyWait RWin ; Wait for [ Right-Win ] to be released Sleep 10 } ; ; BrowserHover ; |--> Hover the mouse over a target area to trigger specific browser-based effects (Javascript on-hover, on cursor entry, on cursor exit, etc.) ; BrowserHover() { Global TrayIcon_Cached Global TrayIcon_Default Global TrayIcon_Gray CoordMode, Mouse, Screen SetDefaultMouseSpeed, 0 SetControlDelay, -1 AwaitModifierKeyup() TrayIcon := TrayIcon_Cached MoveDistance := 1 Updated_TrayIcon := 0 HoverAfter_Seconds := 240 If (FileExist(TrayIcon_Cached)) { BusyIcon := TrayIcon_Cached } Else { BusyIcon := TrayIcon_Default } If (FileExist(TrayIcon_Gray)) { WaitIcon := TrayIcon_Gray } Else { WaitIcon := TrayIcon_Default } Menu("Tray","Icon",WaitIcon) Loop { If (A_TimeIdlePhysical >= (HoverAfter_Seconds * 1000)) { If (Updated_TrayIcon==0) { Menu("Tray","Icon",BusyIcon) Updated_TrayIcon := 1 } MouseMove, %MoveDistance%, 0, 0, R Sleep 1000 MouseMove, -%MoveDistance%, 0, 0, R } Else { If (Updated_TrayIcon==1) { Menu("Tray","Icon",WaitIcon) Updated_TrayIcon := 0 } } Sleep 15000 } } ; ; ClearSplashText ; |--> If called with a positive [ %Period% ], wait [ %Period% ] milliseconds, executes [ %Label% ], then repeats (until explicitly cancelled) ; |--> If called with a negative [ %Period% ], wait [ %Period% ] milliseconds, executes [ %Label% ], then returns ; ClearSplashText(Period) { Label := "RemoveSplashText" SetTimer, %Label%, -%Period% Return } ; ; ClearTooltip ; |--> If called with a positive [ %Period% ], wait [ %Period% ] milliseconds, executes [ %Label% ], then repeats (until explicitly cancelled) ; |--> If called with a negative [ %Period% ], wait [ %Period% ] milliseconds, executes [ %Label% ], then returns ; ClearTooltip(Period) { Label := "RemoveToolTip" SetTimer, %Label%, -%Period% Return } ; ; ClickLoop ; |--> Send left click indefinitely until script is cancelled, with a long enough break between clicks to not make it impossible to stop ; ClickLoop(MouseX,MouseY,Timeout) { CoordMode, Mouse, Screen SetDefaultMouseSpeed, 0 SetKeyDelay, 0, -1 If (Timeout < 250) { Timeout := 250 } Loop { Sleep %Timeout% MouseClick, Left, %MouseX%, %MouseY% } Return } ; ; CreateCitationsFooter ; |--> Creates a block of text designed for placement at the bottom (footer) of a document, ; script, etc. which contains Web-Urls to sources which assisted in building said script ; CreateCitationsFooter() { AwaitModifierKeyup() ; Wait until all modifier keys are released Revert_A_KeyDelay := A_KeyDelay SetKeyDelay, 0, -1 LF := "`n" SendInput % LF SendInput {Space}{Shift Down}{Home}{Shift Up}{Delete} SendInput % LF SendInput % "------------------------------------------------------------" SendInput {LControl Down}{q}{LControl Up} SendInput % LF SendInput {LControl Down}{q}{LControl Up} SendInput {End}{Shift Down}{Home}{Right}{Shift Up} SendInput % LF SendInput % "Citation(s)" SendInput {LControl Down}{q}{LControl Up} SendInput % LF SendInput {LControl Down}{q}{LControl Up} SendInput {End}{Shift Down}{Home}{Right}{Shift Up} SendInput % LF SendInput % "domain | `"title`" | url" SendInput {LControl Down}{q}{LControl Up} SendInput % LF SendInput {LControl Down}{q}{LControl Up} SendInput {End}{Shift Down}{Home}{Right}{Shift Up} SendInput % LF SendInput % "------------------------------------------------------------" SendInput {LControl Down}{q}{LControl Up} SendInput {Up 2}{Left 26}{Space 2} SendInput {End}{Shift Down}{Left 3}{Shift Up} SetKeyDelay, %Revert_A_KeyDelay%, -1 Return } ; ; CommentCurrentLine ; |--> Uses Ctrl + Q hotkey to comment the current line (WITH a leading space) in a given IDE (Notepad++/VS-Code) ; CommentCurrentLine() { Send {LControl Down}{q}{LControl Up} Sleep 10 Return } ; ; CommentCurrentLine_NoSpace ; |--> Uses Ctrl + Q hotkey to comment the current line (WITHOUT a leading space) in a given IDE (Notepad++/VS-Code) ; CommentCurrentLine_NoSpace() { Send {Home}{LControl Down}{q}{LControl Up}{Backspace} Sleep 10 Return } ; ; DoLogging ; |--> Log given text to target file ; DoLogging(LogText) { ; FormatTime,TIMESTAMP,,yyyyMMddTHHmmss OutputLogfile := "C:\Users\" A_UserName "\Desktop" "\debug-logging.txt" FileAppend, ( %LogText% ), %OutputLogfile% Return } ; ; Duplicate_Keypress ; |--> Get user-entered keypress & repeatedly send a duplicate (mock) keypress indefinitely afterwards ; Duplicate_Keypress() { KeyPressed := "" Loop { TooltipOutput := ( "Press a key (will be duplicated)" ) If (DebugMode == 1) { TooltipOutput := ( TooltipOutput "`n" "KeyPressed = [" KeyPressed "]" "`n" "ErrorLevel = [" ErrorLevel "]" ) } ToolTip, % ( TooltipOutput ) ; Get the key to duplicate from the user Input, KeyPressed, "L1 T1" If (ErrorLevel == "Max") { ; Exhaustive list of values for [ ErrorLevel ] regarding the [ Input ] AHK command: https://www.autohotkey.com/docs/commands/Input.htm#Error_Handling Break } } TooltipOutput := ( "Spamming the [ " KeyPressed " ] key" ) Loop { ToolTip, % ( TooltipOutput ) Send % KeyPressed Sleep 10 } ClearTooltip(10) Return } ; ; EscapeSpecialCharacters ; |--> Escape Special characters "{}!^#+" in Curly-Braces "{" CHAR_HERE "}" ; |--> Intended to help AHK type curly-brace characters correctly (and not interpret them as open/close block arguments ; |--> Also intended to help AHK type CTRL (^), ALT (!), SHIFT (+), and WINKEY (#) special characters correctly (and not interpret them as modifier keypresses when parsing strings) ; EscapeSpecialCharacters(StringToEscape:="") { ReturnedString := "" StringConsolidated := RegexConsolidateNewlines(StringToEscape) If InStr(StringConsolidated, "`n") { ; Iterate over each line in the string For EachKey, EachLine in StrSplit(StringConsolidated,"`n") { ; Multi-line string - Iterate over each character in each line Loop, Parse, %EachLine% { If (A_LoopField == "{") { ReturnedString := ReturnedString "{{}" } Else If (A_LoopField == "}") { ReturnedString := ReturnedString "{}}" } Else If ((A_LoopField=="^")||(A_LoopField=="+")||(A_LoopField=="!")||(A_LoopField=="#")) { ReturnedString := ReturnedString "{" A_LoopField "}" } Else { ReturnedString := ReturnedString A_LoopField } } ReturnedString := ReturnedString "`n" } ; After the for-each loop completes, make sure to trim the final trailing newline before sending the string out the door ReturnedString := SubStr(ReturnedString, 1, -1) } Else { ; Single-line string - Iterate over each character in each line Loop, Parse, %StringConsolidated% { If (A_LoopField == "{") { ReturnedString := ReturnedString "{{}" } Else If (A_LoopField == "}") { ReturnedString := ReturnedString "{}}" } Else If ((A_LoopField=="^")||(A_LoopField=="+")||(A_LoopField=="!")||(A_LoopField=="#")) { ReturnedString := ReturnedString "{" A_LoopField "}" } Else { ReturnedString := ReturnedString A_LoopField } } } Return ReturnedString } ; ; Get_ahk_id_from_pid ; |--> Input: WinPID to Target ; |--> Returns ahk_id (process-handle) for AHK back-end control-based calls ; Get_ahk_id_from_pid(WinPid) { SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring ControlGet, OutputVar, Hwnd,,, ahk_pid %WinPid% Return ahk_id %OutputVar% ; dat_ahk_id=ahk_id %output_var% ; Return dat_ahk_id } ; ; Get_ahk_id_from_title ; |--> Input: WinTitle to Target, WinTitle to Exclude from Targeting ; |--> Returns ahk_id (process-handle) for AHK back-end control-based calls ; Get_ahk_id_from_title(WinTitle,ExcludeTitle) { SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring ControlGet, OutputVar, Hwnd,,, %WinTitle%,, %ExcludeTitle% Return ahk_id %OutputVar% } ; ; GetCommandOutput ; |--> Returns the standard output returned from a CMD (ComSpec) command ; GetCommandOutput(CMD_Command) { WScript_Shell_StdOut := RunWaitMany(CMD_Command) Return WScript_Shell_StdOut } ; ; GetPID ; |--> Returns PID if process IS found ; |--> Returns 0 if process is NOT found ; GetPID(ProcName) { ProcessExist,, %ProcName% ; ProcessExist, OutputVar, %ProcName% Return %ErrorLevel% } ; ; GetRandomString ; |--> Generate a random string of desired length ; GetRandomString(DesiredStringLength:=20, EnableNumbers:=1, EnableLowercaseLetters:=1, EnableUppercaseLetters:=0, EnableSpecialCharacters:=0) { ReturnedString := "" AllowedCharacters := "" AllNumbers := "0123456789" If (EnableNumbers == 1) { AllowedCharacters := ( AllowedCharacters . AllNumbers ) } Else { EnableNumbers := 0 } AllLowercase := "abcdefghijklmnopqrstuvwxyz" If (EnableLowercaseLetters == 1) { AllowedCharacters := ( AllowedCharacters . AllLowercase ) } Else { EnableLowercaseLetters := 0 } AllUppercase := "ABCDEFGHIJKLMNOPQRSTUVWXYZ" If (EnableUppercaseLetters == 1) { AllowedCharacters := ( AllowedCharacters . AllUppercase ) } Else { EnableUppercaseLetters := 0 } AllSpecial := "!@#$`%^&*" If (EnableSpecialCharacters == 1) { AllowedCharacters := ( AllowedCharacters . AllSpecial ) } Else { EnableSpecialCharacters := 0 } MinimumCharacters_NeededForCharTypes := ( EnableNumbers + EnableLowercaseLetters + EnableUppercaseLetters + EnableSpecialCharacters ) If ( DesiredStringLength < MinimumCharacters_NeededForCharTypes ) { MsgBox, 0, A_ThisFunc, % ( "Error - String must be at least " MinimumCharacters_NeededForCharTypes " characters long (to meet character type requirements)" ) } Else If (StrLen(AllowedCharacters) <= 0) { MsgBox, 0, A_ThisFunc, % ( "Error - No character types were selected (unable to generate a random string from nothing)" ) } Else { ; Enforce that at least 1 of each allowed character type appears in the string Pos_ForceNum := -1 Pos_ForceLower := -1 Pos_ForceUpper := -1 Pos_ForceSpecial := -1 If (EnableUppercaseLetters == 1) { ; Set the first character to an Uppercase letter (most preferred) Pos_ForceUpper := 0 } Else If (EnableLowercaseLetters == 1) { ; Set the first character to an Lowercase letter Pos_ForceLower := 0 } Else If (EnableNumbers == 1) { ; Set the first character to an Number Pos_ForceNum := 0 } Else If (EnableSpecialCharacters == 1) { ; Set the first character to an Special character Pos_ForceSpecial := 0 } ; Force at least one number (if allowed in call) If (EnableNumbers == 1) { While ((Pos_ForceNum == -1) || (Pos_ForceNum==Pos_ForceLower) || (Pos_ForceNum==Pos_ForceUpper) || (Pos_ForceNum==Pos_ForceSpecial)) { Random, Pos_ForceNum, 0, % (DesiredStringLength-1) } } ; Force at least one lowercase letter (if allowed in call) If (EnableLowercaseLetters == 1) { While ((Pos_ForceLower == -1) || (Pos_ForceLower==Pos_ForceNum) || (Pos_ForceLower==Pos_ForceUpper) || (Pos_ForceLower==Pos_ForceSpecial)) { Random, Pos_ForceLower, 0, % (DesiredStringLength-1) } } ; Force at least one uppercase letter (if allowed in call) Pos_ForceUpper := -1 If (EnableUppercaseLetters == 1) { While ((Pos_ForceUpper == -1) || (Pos_ForceUpper==Pos_ForceNum) || (Pos_ForceUpper==Pos_ForceLower) || (Pos_ForceUpper==Pos_ForceSpecial)) { Random, Pos_ForceUpper, 0, % (DesiredStringLength-1) } } ; Force at least one special character (if allowed in call) Pos_ForceSpecial := -1 If (EnableSpecialCharacters == 1) { While ((Pos_ForceSpecial == -1) || (Pos_ForceSpecial==Pos_ForceNum) || (Pos_ForceSpecial==Pos_ForceLower) || (Pos_ForceSpecial==Pos_ForceUpper)) { Random, Pos_ForceSpecial, 0, % (DesiredStringLength-1) } } ; Build a random string MaxLoopIterations := ( DesiredStringLength * 1000 ) PreviousChar := "" Loop MaxLoopIterations { If (StrLen(ReturnedString) >= DesiredStringLength) { Break } Else { EachLoop_AllowedChars := AllowedCharacters If (StrLen(ReturnedString) == Pos_ForceNum) { EachLoop_AllowedChars := AllNumbers ; Force next char to be a number } Else If (StrLen(ReturnedString) == Pos_ForceLower) { EachLoop_AllowedChars := AllLowercase ; Force next char to be a lowercase letter } Else If (StrLen(ReturnedString) == Pos_ForceUpper) { EachLoop_AllowedChars := AllUppercase ; Force next char to be an uppercase letter } Else If (StrLen(ReturnedString) == Pos_ForceSpecial) { EachLoop_AllowedChars := AllSpecial ; Force next char to be a special character } ; Generate a random index based off of the allowed characters' string as a character array, and use that for the 'random' component Random, RandomCharacterIndex, 1, % ( StrLen(EachLoop_AllowedChars) ) NextChar := SubStr(EachLoop_AllowedChars, RandomCharacterIndex, 1) If (NextChar != PreviousChar) { ; Only append the next character if its not a repeat of the last character ReturnedString .= NextChar PreviousChar := NextChar } } } } Return "%ReturnedString%" } ; ; GetTimestamp ; |--> Returns the current datetime formatted as-needed ; | ; |--> Example: GetTimestamp("yyyyMMddTHHmmss") ; |--> Example: GetTimestamp("yyyy.MM.dd-HH.mm.ss") ; |--> Example: GetTimestamp("yyyy.MM.dd HH:mm:ss") ; |--> Example: GetTimestamp("yyyy-MM-ddTHH-mm-ss") ; GetTimestamp(YMD_Separator:="-", HMS_Separator:=":", DT_Field_Separator:="T") { ; Global RFC3339_YearMonthDay_Separator ; Global RFC3339_HMS_Separator ; Global RFC3339_DateAndTimeField_Separator Timestamp_Format := "yyyy" YMD_Separator "MM" YMD_Separator "dd" DT_Field_Separator "HH" HMS_Separator "mm" HMS_Separator "ss" Return FormatTime("",Timestamp_Format) } ; ; GetTimezoneOffset ; |--> Returns the timezone with [ DateTime +/- Zulu-Offset ] ; GetTimezoneOffset(ByRef Output_TZ, HMS_Separator:=":", UTC_ReplacementStr:="Z", StripCharacter:=".") { Global RFC3339_UTC_ZeroHourReplacement Time_CurrentTZ := A_Now Time_UTC := A_NowUTC TZ_UTC_LocalOffset := DateDiff(Time_CurrentTZ, Time_UTC, "Minutes") TZ_UTC_HourOffset := Floor(TZ_UTC_LocalOffset/60) TZ_UTC_MinuteOffset := TZ_UTC_LocalOffset - TZ_UTC_HourOffset*60 ; +/- Timezone ahead/behind UTC determination TZ_UTC_PositiveNegative_Sign := "" If (TZ_UTC_HourOffset<0.0) { TZ_UTC_PositiveNegative_Sign := "-" TZ_UTC_HourOffset *= -1 } Else { TZ_UTC_PositiveNegative_Sign := "+" } ; Hours - Left-Pad with zeroes as-needed TZ_UTC_HourOffset_Padded := Format("{:02}", TZ_UTC_HourOffset) ; Minutes - Left-Pad with zeroes as-needed TZ_UTC_MinuteOffset_Padded := Format("{:02}", TZ_UTC_MinuteOffset) Output_TZ := "" If ((TZ_UTC_HourOffset = 0.0) && (StrLen(UTC_ReplacementStr) > 0)) { ; Replacement-string to use for timezone when the UTC timezone (UTC+00:00) is output Output_TZ := UTC_ReplacementStr } Else { Output_TZ := Output_TZ TZ_UTC_PositiveNegative_Sign Output_TZ := Output_TZ TZ_UTC_HourOffset_Padded Output_TZ := Output_TZ HMS_Separator Output_TZ := Output_TZ TZ_UTC_MinuteOffset_Padded } If (StrLen(StripCharacter) > 0) { Output_TZ := StrReplace(Output_TZ, StripCharacter, "") } Return } ; ; GetTimezoneOffset_P ; |--> Returns the timezone with "P" instead of "+", for fields which only allow alphanumeric with hyphens ; GetTimezoneOffset_P(ByRef Output_TZ_P) { Output_TZ_P := "" GetTimezoneOffset(Output_TZ_P) Output_TZ_P := StrReplace(Output_TZ_P, "+", "P") Return } ; ; GetWindowSpecs ; |--> Gets Specs for currently-active window ; GetWindowSpecs(WinTitle:="A") { ; Set the Gui-identifier (e.g. which gui-popup is affected by gui-based commands, such as [ Gui, ... ] and [ LV_Add(...) ]) Gui, WindowSpecs:Default Gui, Destroy Win_ahk_id := WinGetID(WinTitle) Win_title := WinGetTitle("ahk_id %Win_ahk_id%") Win_text := WinGetText("ahk_id %Win_ahk_id%") Win_ahk_class := WinGetClass("ahk_id %Win_ahk_id%") Win_ahk_pid := WinGetPID("ahk_id %Win_ahk_id%") Win_ahk_exe := WinGetProcessName("ahk_id %Win_ahk_id%") Win_fullpath := WinGetProcessPath("ahk_id %Win_ahk_id%") Win_control_names := WinGetControls("ahk_id %Win_ahk_id%") ; Get all control names in this window Win_size_state := WinGet_size_state("ahk_id %Win_ahk_id%") WinGetPos(xpos, ypos, Win_width, Win_height, "ahk_id %Win_ahk_id%") ; Determine the longest text-field, and base the width of the Gui off of the number of characters it contains Win_longest_field := 0 Win_longest_field := StrLen_Max(Win_longest_field, Win_title) Win_longest_field := StrLen_Max(Win_longest_field, Win_fullpath) Win_longest_field := StrLen_Max(Win_longest_field, Win_control_names) Win_longest_field := StrLen_Max(Win_longest_field, Win_ahk_class) Win_is_win10_app := WinGet_is_win10_app(WinTitle) If (Win_is_win10_app == 1) { ; Get the Win10-App's stats Win10_ahk_id := WinGet_ahk_id(WinTitle) Win10_title := WinGetTitle("ahk_id %Win10_ahk_id%") Win10_text := WinGetText("ahk_id %Win10_ahk_id%") Win10_ahk_class := WinGetClass("ahk_id %Win10_ahk_id%") Win10_ahk_pid := WinGetPID("ahk_id %Win10_ahk_id%") Win10_ahk_exe := WinGetProcessName("ahk_id %Win10_ahk_id%") Win10_fullpath := WinGetProcessPath("ahk_id %Win10_ahk_id%") Win10_control_names := WinGetControls("ahk_id %Win10_ahk_id%") ; Get all control names in this window Win10_size_state := WinGet_size_state("ahk_id %Win10_ahk_id%") WinGetPos(Win10_xpos, Win10_ypos, Win10_Width, Win10_Height, "ahk_id %Win10_ahk_id%") ; Update the longest text-field Win_longest_field := StrLen_Max(Win_longest_field, Win10_title) Win_longest_field := StrLen_Max(Win_longest_field, Win10_fullpath) Win_longest_field := StrLen_Max(Win_longest_field, Win10_control_names) Win_longest_field := StrLen_Max(Win_longest_field, Win10_ahk_class) } ; --- TABLE - TOTAL WIDTH --- GUI_LONGEST_FIELD := StrLen(Win_longest_field) GUI_BASE_WIDTH := 200 If (Win_is_win10_app == 1) { GUI_BASE_WIDTH := GUI_BASE_WIDTH + 64 } GUI_WIDTH := GUI_BASE_WIDTH + Ceil( GUI_LONGEST_FIELD * 8 ) ; <-- 8 to 8.5 seems to be the perfect character-width multiplier for the GUI using font 'Tahoma' ; --- TABLE - TOTAL ROWS --- GUI_ROWCOUNT := 1 ; Header-Row GUI_ROWCOUNT := GUI_ROWCOUNT + 14 ; Win-Rows If (Win_is_win10_app == 1) { GUI_ROWCOUNT := GUI_ROWCOUNT + 11 ; Win10-Rows } If (DebugMode == 1) { GUI_ROWCOUNT := GUI_ROWCOUNT + 3 ; Debug-Rows } ; --- TABLE - COLORS --- GUI_BACKGROUND_COLOR := "1E1E1E" GUI_TEXT_COLOR := "FFFFFF" ; --- TABLE - FINAL CONFIG --- ( Gui Listview has many options under its "G-Label" callback - See more @ https://www.autohotkey.com/docs/commands/ListView.htm#G-Label_Notifications_Secondary ) GUI_OPT := "r" GUI_ROWCOUNT GUI_OPT := GUI_OPT " w" GUI_WIDTH GUI_OPT := GUI_OPT " gGetWindowSpecs_OnClick_LV_WindowSpecs" GUI_OPT := GUI_OPT " Background" GUI_BACKGROUND_COLOR GUI_OPT := GUI_OPT " C" GUI_TEXT_COLOR GUI_OPT := GUI_OPT " Grid" GUI_OPT := GUI_OPT " NoSortHdr" ; GUI_OPT = %GUI_OPT% AltSubmit ; Draw the 'ListView' (grid/table) with two columns ; |--> Note that [ Gui, {configs...} ] declarations must be on the PREVIOUS LINE before [ Gui, Add, ... ] Gui, Font, s10, Tahoma Gui, Font, s10, Consolas Gui, Font, s10, Courier New Gui, Font, s10, Open Sans Gui, Font, s10, Fira Code Gui, Color, 1E1E1E Gui, Add, ListView, %GUI_OPT%, Key|Value LV_Add("", "", "") LV_Add("", "Win_title", Win_title) LV_Add("", "Win_text", Win_text) LV_Add("", "Win_ahk_class", Win_ahk_class) LV_Add("", "Win_ahk_exe", Win_ahk_exe) LV_Add("", "Win_ahk_id", Win_ahk_id) LV_Add("", "Win_ahk_pid", Win_ahk_pid) LV_Add("", "Win_fullpath", Win_fullpath) LV_Add("", "Win_control_names", Win_control_names) LV_Add("", "Win_size_state", Win_size_state) ; LV_Add("", "xpos", xpos) ; LV_Add("", "ypos", ypos) ; LV_Add("", "Width", Win_width) ; LV_Add("", "height", Win_height) LV_Add("", "xpos, ypos", ( xpos ", " ypos ) ) LV_Add("", "width, height", ( Win_width ", " Win_height ) ) ; LV_Add("", "Mimic in AHK", "WinMove,,,%xpos%,%ypos%,%Win_width%,%Win_height%") ; Handle Windows 10 'apps' (applications) alongside 'normal' Windows executables/process-windows LV_Add("", "", "") LV_Add("", "Is Win10 App?", ((Win_is_win10_app==1) ? ("Yes"):("No"))) If (Win_is_win10_app == 1) { ; Show the Win10-App's stats LV_Add("", "Win10_title", Win10_title) LV_Add("", "Win10_text", Win10_text) LV_Add("", "Win10_ahk_class", Win10_ahk_class) LV_Add("", "Win10_ahk_exe", Win10_ahk_exe) LV_Add("", "Win10_ahk_id", Win10_ahk_id) LV_Add("", "Win10_ahk_pid", Win10_ahk_pid) LV_Add("", "Win10_fullpath", Win10_fullpath) LV_Add("", "Win10_control_names", Win10_control_names) LV_Add("", "Win10_size_state", Win10_size_state) ; LV_Add("", "Win10_xpos", Win10_xpos) ; LV_Add("", "Win10_ypos", Win10_ypos) ; LV_Add("", "Win10_Width", Win10_Width) ; LV_Add("", "Win10_Height", Win10_Height) LV_Add("", "Win10_xpos, Win10_ypos", ( Win10_xpos ", " Win10_ypos ) ) LV_Add("", "Win10_Width, Win10_Height", ( Win10_Width ", " Win10_Height ) ) } If (DebugMode == 1) { LV_Add("", "", "") LV_Add("", "GUI_LONGEST_FIELD", GUI_LONGEST_FIELD) LV_Add("", "GUI_WIDTH", GUI_WIDTH) ; LV_Add("", "GUI_OPT", GUI_OPT) } LV_Add("", "", "") LV_ModifyCol(1, "AutoHdr Text Left") LV_ModifyCol(2, "AutoHdr Text Left") ; LV_ModifyCol() ; Auto-size each column to fit its contents. ; Display the window and return. The script will be notified whenever the user double clicks a row. Gui, Show Return } ; ; GetWindowSpecs_OnClick_LV_WindowSpecs ^^^ NEEDED BY GET_WINDOW_SPECS() ^^^ ; |--> Sub-Function of "GetWindowSpecs()" ; GetWindowSpecs_OnClick_LV_WindowSpecs() { ; Obj_EventTriggers := {"Normal": 1, "DoubleClick": 1, "RightClick": 1, "R": 1} Obj_EventTriggers := {"DoubleClick": 1, "RightClick": 1, "R": 1} If (Obj_EventTriggers[A_GuiEvent]) { LV_GetText(KeySelected, A_EventInfo, 1) ; Grab the key (col. 1) associated with the double-click event LV_GetText(ValSelected, A_EventInfo, 2) ; Grab the val (col. 2) associated with the double-click event MsgBox, 4, %A_ScriptName%, (LTrim You selected: %ValSelected% Copy this to the clipboard? ) If (A_MsgBoxResult = "Yes") { Clipboard := ValSelected } ; Gui, WindowSpecs:Default ; Gui, Destroy } ; DEBUGGING-ONLY (Set "%LV_Verbosity%" to 1 to enable verbose debug-logging) LV_Verbosity := 0 If ( LV_Verbosity = 1 ) { TooltipOutput := "A_GuiEvent=[" A_GuiEvent "], A_EventInfo=[" A_EventInfo "]" ToolTip, %TooltipOutput% SetTimer, RemoveToolTip, -2500 } Return } ; ; IfProcessExist (proxy-function for GetPID(...)) ; |--> Returns True if process IS found ; |--> Returns False if process is NOT found ; IfProcessExist(ProcName) { Return (GetPID(ProcName)>0) ? True : False } ; ; LockWorkstation ; |--> Lock the Workstation and turn-off/activate-lower-power-mode on monitors ; LockWorkstation() { DllCall("LockWorkStation") Sleep 10 Monitor_ActivateLowPowerMode() ; Monitor_PowerOff() Return } ; ; GetMicroseconds ; |--> Gets the current timestamp's fractions-of-a-second, down to the 6th digit (microseconds-precision) ; |--> Example call: ; GetMicroseconds(CurrentMicroseconds) ; GetMicroseconds(ByRef OutputVar) { vIntervals := 0 DllCall("kernel32\GetSystemTimeAsFileTime", "Int64*",vIntervals) ; 1 interval = 0.1 microseconds OutputVar := SubStr(Format("{:00}00", Mod(vIntervals, 10000000)), 1, 6) Return } ; ; GetMilliseconds ; |--> Gets the current timestamp's fractions-of-a-second, down to the 3rd digit (millisecond-precision) ; |--> Example call: ; GetMilliseconds(CurrentMilliseconds) ; GetMilliseconds(ByRef OutputVar) { OutputVar := A_MSec Return } ; ; GetNanoseconds ; |--> Gets the current timestamp's fractions-of-a-second, down to the 9th digit (pseudo-nanosecond-precision - max-precision is actually only 7 digits past decimal, e.g. per-100-nanoseconds) ; |--> Example call: ; GetNanoseconds(CurrentNanoseconds) ; GetNanoseconds(ByRef OutputVar) { vIntervals := 0 DllCall("kernel32\GetSystemTimeAsFileTime", "Int64*",vIntervals) ; 1 interval = 100 nanoseconds ; vDate := 1601 ; EnvAdd, vDate, % vIntervals//10000000, S ; autohotkey.com | "EnvAdd" | https://www.autohotkey.com/docs/commands/EnvAdd.htm OutputVar := Format("{:07}00", Mod(vIntervals, 10000000)) Return } ; ; Monitor_ActivateLowPowerMode ; |--> [ 0x112 ] targets [ WM_SYSCOMMAND ] - https://docs.microsoft.com/en-us/windows/win32/menurc/wm-syscommand ; |--> [ 0xF170 ] targets [ SCMONITORPOWER ] ; |--> Sending a value of [ 1 ] sends [ activate low-power mode ] to attached monitor(s) ; Monitor_ActivateLowPowerMode() { DllCall("LockWorkStation") Sleep 10 SendMessage, 0x112, 0xF170, 1,, Program Manager Return } ; ; Monitor_PowerOff ; |--> [ 0x112 ] targets [ WM_SYSCOMMAND ] - https://docs.microsoft.com/en-us/windows/win32/menurc/wm-syscommand ; |--> [ 0xF170 ] targets [ SCMONITORPOWER ] ; |--> Sending a value of [ 2 ] sends [ power off ] to attached monitor(s) ; Monitor_PowerOff() { DllCall("LockWorkStation") Sleep 10 SendMessage, 0x112, 0xF170, 2,, Program Manager Return } ; ; Monitor_PowerOn ; |--> [ 0x112 ] targets [ WM_SYSCOMMAND ] ; |--> [ 0xF170 ] targets [ SCMONITORPOWER ] ; |--> Sending a value of [ -1 ] sends [ power on ] to attached monitor(s) ; Monitor_PowerOn() { DllCall("LockWorkStation") Sleep 10 SendMessage, 0x112, 0xF170, -1,, Program Manager Return } ; ; Monitor_ShowScreenSaver ; |--> [ 0x112 ] targets [ WM_SYSCOMMAND ] - https://docs.microsoft.com/en-us/windows/win32/menurc/wm-syscommand ; |--> [ 0xF140 ] targets [ SC_SCREENSAVE ] ; |--> Sending a value of [ 2 ] sends [ power off ] to attached monitor(s) ; Monitor_ShowScreenSaver() { SendMessage, 0x112, 0xF140, 0,, Program Manager ; | ; |--> [ 0x112 ] targets [ WM_SYSCOMMAND ] - https://docs.microsoft.com/en-us/windows/win32/menurc/wm-syscommand ; | ; |--> [ 0xF140 ] targets [ SC_SCREENSAVE ] ; Return } ; ; MoveIt ; |--> "I wanted to be able to set a window to the top half or bottom half of a monitor just like windows 7 can do with left and right. I couldn't find a good script that worked well with my 3 monitor landscape / portrait layout. So I wrote one." -MrMaxP ; |--> https://www.autohotkey.com/board/topic/108780-move-window-to-half-quarter-of-current-monitor/?p=648327 ; MoveIt(Destination_Direction:="Left", Destination_Size:="Half", Destination_MonitorNumber:="UseCurrentMonitor", WinTitle:="A", WinText:="") { ; Destination_Direction := [ "Left", "Right", "Top", "Bottom", "Maximized", "Restored" ] ; Destination_Size := [ "Half","Left","Right","Top","Bottom" ] Global DebugMode ; Check if action to be performed is a simple window restore If (Destination_Direction=="Restored") { ; ; Set window state to "Restored" ; |--> Do not handle window restoration onto other monitors, as the dimensions of a window could skew it outside of the bounds of target monitor (and I'm too lazy to do the coding for making sure the window from monitor "1" (for example) fits onto a potentially-smaller monitor "2", but also if you resize the window in the process, it wouldn't truly be a 'restore' action anymore, so yeah just skip the 'feature' of restoring to any monitor other than the window's current monitor) ; WinRestore(WinTitle, WinText) } Else { ; Get the window's current xpos, ypos, width & height WinGetPos(Win_XPos, Win_YPos, Win_Width, Win_Height, WinTitle, WinText) ; Check if window is Maximized/Minimized, then prep accordingly If (WinGetMinMax(WinTitle,WinText)==1) { ; Window is Maximized --> Adjust its xpos and ypos by +8 (as Windows (for some reason) sets the top-left coords of maximized windows to -8,-8 x,y relative to the top-left coords of the monitor it's on) ; Win_XPos := Win_XPos + 8 ; Win_YPos := Win_YPos + 8 } Else If ((WinGetMinMax(WinTitle,WinText)==-1) || ((WinGetMinMax(WinTitle,WinText)!=1) && (Win_Width < -8) && (Win_Height < -8))) { ; Note: Maximized xpos,ypos == -8,-8 (commonly) ; Window is Minimized (which prevents AHK from obtaining the window's current xpos, ypos, width & height) --> Restore it WinRestore(WinTitle, WinText) Sleep 750 WinGetPos(Win_XPos, Win_YPos, Win_Width, Win_Height, WinTitle, WinText) } Do_Maximized := False ; Calculate the top center edge Win_Center_XPos := Win_XPos + Win_Width/2 Win_Center_YPos := Win_YPos + 20 ; Compensate for ??? with this 20px add? taskbar is 40px... Win_Center_MonitorNumber := 0 WinMove_XPos := -1 WinMove_YPos := -1 WinMove_Width := -1 WinMove_Height := -1 Matched_MonitorNumber := -1 If ((Destination_MonitorNumber!="UseCurrentMonitor") && ("%Destination_MonitorNumber%"!="1") && (MonitorGetCount()==1)) { ; If there's only one monitor, then downgrade any monitor "2" & monitor "3" requests to use monitor "1", instead Destination_MonitorNumber:=1 } Loop % MonitorGetCount() { Each_MonitorNumber := A_Index ; Docs: "Check if the specified monitor exists and optionally retrieve the bounding coordinates of its working area" - https://lexikos.github.io/v2/docs/commands/MonitorGetWorkArea.htm MonitorGetWorkArea(Each_MonitorNumber, EachMonitor_LeftCoord, EachMonitor_TopCoord, EachMonitor_RightCoord, EachMonitor_BottomCoord) ; Determine if the current iteration's monitor is the destination monitor MoveTo_ThisMonitor := False ; Determine if the center of target window is currently located within the bounds of this monitor's work area If ((Win_Center_XPos>=EachMonitor_LeftCoord) && (Win_Center_XPos<=EachMonitor_RightCoord) && (Win_Center_YPos>=EachMonitor_TopCoord) && (Win_Center_YPos<=EachMonitor_BottomCoord)) { ; Window is located on this monitor Win_Center_MonitorNumber := A_Index If (Destination_MonitorNumber=="UseCurrentMonitor") { ; Set the destination monitor equal to the window's current monitor MoveTo_ThisMonitor := True } } If (Destination_MonitorNumber == Each_MonitorNumber) { ; Set the destination monitor equal to a predefined monitor MoveTo_ThisMonitor := True } If (MoveTo_ThisMonitor == True) { ; Monitor is to be used as the window's destination Matched_MonitorNumber := Each_MonitorNumber EachMonitor_Width := (EachMonitor_RightCoord-EachMonitor_LeftCoord) EachMonitor_Height := (EachMonitor_BottomCoord-EachMonitor_TopCoord) EachMonitor_HalfWidth := (EachMonitor_Width / 2) EachMonitor_HalfHeight := (EachMonitor_Height / 2) EachMonitor_Center_XPos := EachMonitor_LeftCoord + EachMonitor_HalfWidth EachMonitor_Center_YPos := EachMonitor_TopCoord + EachMonitor_HalfHeight If (Destination_Direction=="Maximized") { ; Set window state to "Maximized" Do_Maximized := True ; WinMove_XPos := EachMonitor_LeftCoord - 8 ; WinMove_YPos := EachMonitor_TopCoord - 8 ; WinMove_Width := EachMonitor_Width + 16 ; WinMove_Height := EachMonitor_Height + 16 WinMove_XPos := EachMonitor_LeftCoord WinMove_YPos := EachMonitor_TopCoord WinMove_Width := EachMonitor_HalfWidth WinMove_Height := EachMonitor_HalfHeight } Else If (Destination_Direction=="Restored") { ; Set window state to "Restored" ; ; HANDLED ABOVE ; } Else { Destination_Combined := ( Destination_Direction "-" Destination_Size ) If (Destination_Combined=="Left-Half") { ; Left Half WinMove_XPos := EachMonitor_LeftCoord WinMove_YPos := EachMonitor_TopCoord WinMove_Width := EachMonitor_HalfWidth WinMove_Height := EachMonitor_Height } Else If (Destination_Combined=="Right-Half") { ; Right Half WinMove_XPos := EachMonitor_Center_XPos WinMove_YPos := EachMonitor_TopCoord WinMove_Width := EachMonitor_HalfWidth WinMove_Height := EachMonitor_Height } Else If (Destination_Combined=="Top-Half") { ; Top Half WinMove_XPos := EachMonitor_LeftCoord WinMove_YPos := EachMonitor_TopCoord WinMove_Width := EachMonitor_Width WinMove_Height := EachMonitor_HalfHeight } Else If (Destination_Combined=="Bottom-Half") { ; Bottom Half WinMove_XPos := EachMonitor_LeftCoord WinMove_YPos := EachMonitor_Center_YPos WinMove_Width := EachMonitor_Width WinMove_Height := EachMonitor_HalfHeight } Else If ((Destination_Combined=="Top-Left") || (Destination_Combined=="Left-Top")) { ; Top-Left Quadrant WinMove_XPos := EachMonitor_LeftCoord WinMove_YPos := EachMonitor_TopCoord WinMove_Width := EachMonitor_HalfWidth WinMove_Height := EachMonitor_HalfHeight } Else If ((Destination_Combined=="Bottom-Left") || (Destination_Combined=="Left-Bottom")) { ; Bottom-Left Quadrant WinMove_XPos := EachMonitor_LeftCoord WinMove_YPos := EachMonitor_Center_YPos WinMove_Width := EachMonitor_HalfWidth WinMove_Height := EachMonitor_HalfHeight } Else If ((Destination_Combined=="Top-Right") || (Destination_Combined=="Right-Top")) { ; Top-Right Quadrant WinMove_XPos := EachMonitor_Center_XPos WinMove_YPos := EachMonitor_TopCoord WinMove_Width := EachMonitor_HalfWidth WinMove_Height := EachMonitor_HalfHeight } Else If ((Destination_Combined=="Bottom-Right") || (Destination_Combined=="Right-Bottom")) { ; Bottom-Right Quadrant WinMove_XPos := EachMonitor_Center_XPos WinMove_YPos := EachMonitor_Center_YPos WinMove_Width := EachMonitor_HalfWidth WinMove_Height := EachMonitor_HalfHeight } If ((WinMove_XPos!=-1) && (WinMove_YPos!=-1) && (WinMove_Width!=-1) && (WinMove_Height!=-1)) { ; ; Half/Quarter sized 'snap' windows --> Add strange proprietary pixel deltas which Windows uses for half-screen sized windows ; |--> May vary for specific applications... ; Win_ahk_exe := WinGetProcessName(WinTitle,WinText) If (Win_ahk_exe=="Code.exe") { ; VS Code ignores this offset, and is sized as-expected (using an offset of 0px) DeltaPixels := 0 } Else If (Win_ahk_exe=="firefox.exe") { ; Firefox uses a 5px base offset DeltaPixels := 5 } Else { ; Everything else seems to use a 5px base offset (default..?) DeltaPixels := 7 } WinMove_XPos := WinMove_XPos - DeltaPixels WinMove_YPos := WinMove_YPos - 0 WinMove_Width := WinMove_Width + ( 2 * DeltaPixels ) WinMove_Height := WinMove_Height + DeltaPixels } } Break } } ; If we are using the "Current" monitor as the destination, then set it respectively If (Destination_MonitorNumber=="UseCurrentMonitor") { Destination_MonitorNumber := Win_Center_MonitorNumber } ; Check for error(s) If ((WinMove_XPos==-1) && (WinMove_YPos==-1) && (WinMove_Width==-1) && (WinMove_Height==-1)) { TextToolTip := "" TextToolTip := TextToolTip " " "`n" TextToolTip := TextToolTip " Error - Invalid Argument(s) passed to function `"" A_ThisFunc "`"" " " "`n" TextToolTip := TextToolTip " |" "`n" TextToolTip := TextToolTip " |--> Call: " A_ThisFunc " ( `"" Destination_Direction "`" , `"" Destination_Size "`" , `"" Destination_MonitorNumber "`" , `"" WinTitle "`" , `"" WinText "`" )" " " "`n" TextToolTip := TextToolTip " |" "`n" TextToolTip := TextToolTip " |--> Script: " A_ScriptFullPath " " "`n" TextToolTip := TextToolTip " " "`n" TextToolTip := TextToolTip " Example call: " A_ThisFunc " ( `"Left`" , `"Half`" , `"UseCurrentMonitor`" , `"A`", `"`" )" " " "`n" TextToolTip := TextToolTip " Example call: " A_ThisFunc " ( `"Maximized`" , `"`" , 2 , `"A`", `"`" )" " " "`n" TextToolTip := TextToolTip " " ShowTooltip(TextToolTip,60000) } Else { If (DebugMode == 1) { MsgBox % "Matched_MonitorNumber=[ " Each_MonitorNumber " ]" "`n" "Do_Maximized=[ " Do_Maximized " ]" "`n" "WinMove ( `"%WinTitle%`" , `"%WinText%`" , , " WinMove_XPos " , " WinMove_YPos " , " WinMove_Width " , " WinMove_Height " )" } If (Do_Maximized==False) { If (WinGetMinMax(WinTitle,WinText)==1) { ; Window is maximized --> Restore it (in preparation for resizing) WinRestore(WinTitle,WinText) } } ; If the window is where it already needs to be, then don't move it WinGetPos(Win_XPos,Win_YPos,Win_Width,Win_Height,WinTitle,WinText) If ((Win_XPos!=WinMove_XPos) || (Win_YPos!=WinMove_YPos) || (Win_Width!=WinMove_Width) || (Win_Height!=WinMove_Height)) { ; Move the window to specified x/y position and resize it to have specified width/height WinMove("%WinTitle%","%WinText%",WinMove_XPos,WinMove_YPos,WinMove_Width,WinMove_Height) Sleep 500 } If (Do_Maximized==True) { ; Maximize the Window on the target monitor If (WinGetMinMax(WinTitle,WinText)!=1) { ; Window is not maximized --> Maximize it WinMaximize(WinTitle,WinText) } } } } Return } ; ; Open_Chrome ; |--> Opens the "Google Chrome" Application ; Open_Chrome() { Global DebugMode SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring FullPath_RunExe := "" FullPath_RunExe_x64 := "C:\Program Files\Google\Chrome\Application\chrome.exe" FullPath_RunExe_x86 := "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" If (FileExist(FullPath_RunExe_x64)) { FullPath_RunExe := FullPath_RunExe_x64 } Else If (FileExist(FullPath_RunExe_x86)) { FullPath_RunExe := FullPath_RunExe_x86 } Win_ahk_exe := "chrome.exe" WinTitle_ahk_exe := "ahk_exe %Win_ahk_exe%" WinTitle := " - Google Chrome" WinText := "Chrome Legacy Window" WinWait_TimeoutSeconds := 5 If (DebugMode == 1) { GetWindowSpecs(WinTitle) Sleep 500 } If ((!WinExist(WinTitle)) && (FullPath_RunExe == "")) { TextToolTip := % "Chrome executable not found (neither x64 or x86 version)" ShowTooltip(TextToolTip,5000) } Else { If ((!WinExist(WinTitle)) && (FullPath_RunExe != "")) { ; Run a NON-admin version of target exe RunExe_NON_Admin(FullPath_RunExe) WinWait, %WinTitle%,, %WinWait_TimeoutSeconds% ; Wait until the specified window exists | https://www.autohotkey.com/docs/commands/WinWait.htm } If (MonitorGetCount()==1) { MoveIt("Right","Half",1,WinTitle) ; Resize window to right-half of monitor #1 } Else { MoveIt("Left","Half",2,WinTitle) ; Resize window to left-half of monitor #2 } WinActivate(WinTitle,WinText) ; Activate the specified window | https://www.autohotkey.com/docs/commands/WinActivate.htm } Return } ; ; Open_ControlPanel_NetworkConnections ; |--> Opens "View Network Connections" ; |--> Open manually via [ Start Menu search for "View Network Connections" ] or [ "Settings (Win10 App)" > "Network & Internet" > "Ethernet" (left menu) > "Change adapter options" (top right) ] ; Open_ControlPanel_NetworkConnections() { WinTitle := "Network Connections" SetTitleMatchMode, 3 ; 3: A window's title must exactly match WinTitle to be a match. AwaitModifierKeyup() ; Wait until all modifier keys are released If (!WinExist(WinTitle)) { If (DebugMode == 1) { TrayTip, AHK, % ( "Opening '" WinTitle "'" ) ; Toast Notification } ; Run % (":" ":" "{7007acc7-3202-11d1-aad2-00805fc1270e}") ; CLSID (Windows Class Identifier) for 'View Network Connections' ; Run % (EnvGet("WINDIR") "\System32\ncpa.cpl") Run % (EnvGet("WINDIR") "\System32\control.exe" " " "ncpa.cpl") WinWait, %WinTitle%,, 10 ; Wait until the specified window exists | https://www.autohotkey.com/docs/commands/WinWait.htm } WinActivate, %WinTitle% ; Activate the specified window | https://www.autohotkey.com/docs/commands/WinActivate.htm Return } ; ; Open_ControlPanel_Sound ; |--> Opens "Sound Control Panel" ; |--> Open manually via [ Start Menu search for "Change system sounds" ] or [ "Settings (Win10 App)" > "System" > "Sound" (left menu) > "Sound Control Panel" (top right) ] ; Open_ControlPanel_Sound(TabToOpen:="Playback") { WinTitle := "Sound" SetTitleMatchMode, 3 ; 3: A window's title must exactly match WinTitle to be a match. AwaitModifierKeyup() ; Wait until all modifier keys are released Tab_Desc := "Playback" Tab_Int := 0 If (TabToOpen=="Playback") { Tab_Desc := "Playback" Tab_Int := 0 } Else If (TabToOpen=="Recording") { Tab_Desc := "Recording" Tab_Int := 1 } Else If (TabToOpen=="Sounds") { Tab_Desc := "Sounds" Tab_Int := 2 } Else If (TabToOpen=="Communications") { Tab_Desc := "Communications" Tab_Int := 3 } Else { Tab_Desc := "Playback" Tab_Int := 0 } If (!WinExist(WinTitle)) { If (DebugMode == 1) { TrayTip, AHK, % ( "Opening '" WinTitle "' > '" Tab_Desc "'" ) ; Toast Notification } Run % (EnvGet("WINDIR") "\System32\control.exe" " " "mmsys.cpl,," Tab_Int) ; Run explorer shell:::{F2DDFC82-8F12-4CDD-B7DC-D4FE1425AA4D} ; CLSID (Windows Class Identifier) for 'Sound Control Panel' ; Run control.exe /name Microsoft.Sound WinWait, %WinTitle%,, 10 ; Wait until the specified window exists | https://www.autohotkey.com/docs/commands/WinWait.htm } WinActivate, %WinTitle% ; Activate the specified window | https://www.autohotkey.com/docs/commands/WinActivate.htm Return } ; ; Open_Exe ; |--> Opens target exeutable & sets its window to be active ; Open_Exe(ExeFullpath) { Global DebugMode Timeout := 10 SplitPath %ExeFullpath%, ExeBasename, ExeDirname, ExeExtension, ExeBasenameNoExt, ExeDrivename If (ProcessExist(ExeBasename) == True) { ; Executable IS running If (DebugMode == 1) { TextToolTip := "Activating `"" ExeBasename "`"" ToolTip, %TextToolTip% ClearTooltip(2000) } ExePID := GetPID(ExeBasename) WinActivate, ahk_pid %ExePID% } Else If (FileExist(ExeFullpath)) { ; Executable NOT running but IS found locally If (DebugMode == 1) { TextToolTip := "Opening `"" ExeBasename "`"" ToolTip, %TextToolTip% ClearTooltip(2000) } ; Run, %ExeFullpath% ExitCode := RunWait(%ExeFullpath%,,, ExePID) ; WinWait "ahk_pid " ExePID ; ExePID := GetPID(ExeBasename) WinActivate, ahk_pid %ExePID% } Else { ; Executable NOT running & NOT found locally If (DebugMode == 1) { TextToolTip := "File not found: `"" ExeFullpath "`"" ToolTip, %TextToolTip% ClearTooltip(2000) } } Return } ; ; Open_VisualStudioCode ; |--> Opens Microsoft's "Visual Studio Code" application (e.g. "VS Code" or "VSCode") - VS Code is a Free Source Code Editor & IDE ; Open_VisualStudioCode() { Global DebugMode SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring ; ------------------------------ FullPath_RunExe := "C:\Windows\System32\notepad.exe" ; Run notepad.exe which is redirected to VS Code through NotepadReplacer (which opens default Workspace in VS Code) Exe_Args:="" ; ------------------------------ ; Win_ahk_exe := "Code.exe" ; WinExist doesn't grab minimized windows by their 'ahk_exe' as-intended ; WinTitle_ahk_exe := "ahk_exe %Win_ahk_exe%" ; WinExist doesn't grab minimized windows by their 'ahk_exe' as-intended ; WinTitle := WinTitle_ahk_exe ; WinExist doesn't grab minimized windows by their 'ahk_exe' as-intended ; WinTitle := WinGetTitle(WinTitle_ahk_exe) ; WinExist doesn't grab minimized windows by their 'ahk_exe' as-intended WinTitle := " - Visual Studio Code" WinText := "Chrome Legacy Window" WinWait_TimeoutSeconds := 5 If (DebugMode == 1) { GetWindowSpecs(WinTitle) Sleep 500 } If (!WinExist(WinTitle)) { ; Run a NON-admin version of target exe RunExe_NON_Admin(FullPath_RunExe, Exe_Args) WinWait, %WinTitle%,,%WinWait_TimeoutSeconds% ; Wait until the specified window exists | https://www.autohotkey.com/docs/commands/WinWait.htm } MoveIt("Left","Half",1,WinTitle) ; Resize window to left-half of monitor #1 WinActivate(WinTitle) ; Activate the specified window | https://www.autohotkey.com/docs/commands/WinActivate.htm Return } ; ; Open_WindowsTerminal ; |--> Opens Microsoft's "Windows Terminal" application - Windows Terminal is a tabbed terminal utility for Windows ; Open_WindowsTerminal() { SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring ; ------------------------------ FullPath_RunExe := "C:\Windows\explorer.exe" Win10_AppName := "Microsoft.WindowsTerminal_8wekyb3d8bbwe" ; App name acquired via powershell call [ (Get-AppxPackage Microsoft.WindowsTerminal).PackageFamilyName; ] Exe_Args := ( "shell:AppsFolder\" Win10_AppName "!App") ; "C:\Windows\explorer.exe" "shell:AppsFolder\Microsoft.WindowsTerminal_8wekyb3d8bbwe!App" ; ------------------------------ ; ;;; Deprecated approach (doesn't work if not acting as an admin while opening it..?) ; FullPath_RunExe := "C:\Program Files\WindowsApps\Microsoft.WindowsTerminal_1.11.2921.0_x64__8wekyb3d8bbwe\wt.exe" ; Acquired via powershell call [ Get-ChildItem ((Get-AppxPackage "*WindowsTerminal*").InstallLocation); ] ; Exe_Args := "" ; ------------------------------ Win_ahk_exe := "WindowsTerminal.exe" WinTitle := "ahk_exe %Win_ahk_exe%" WinText := "DesktopWindowXamlSource" WinWait_TimeoutSeconds := 5 If (DebugMode == 1) { GetWindowSpecs(WinTitle) Sleep 500 } If (!WinExist(WinTitle)) { ; Run a NON-admin version of target exe RunExe_NON_Admin(FullPath_RunExe, Exe_Args) WinWait, %WinTitle%,,%WinWait_TimeoutSeconds% ; Wait until the specified window exists | https://www.autohotkey.com/docs/commands/WinWait.htm } MoveIt("Right","Half",1,WinTitle,WinText) ; Resize window to right-half of monitor #1 WinActivate(WinTitle,WinText) ; Activate the specified window | https://www.autohotkey.com/docs/commands/WinActivate.htm Return } ; ; PasteClipboardAsBinary ; |--> Pastes the current clipboard data as binary-data (as if the user typed it instead of pasting it) ; PasteClipboardAsBinary() { Global DebugMode SetKeyDelay, 0, -1 AwaitModifierKeyup() ; Wait until all modifier keys are released Sleep, 250 Clipboard := ClipboardAll Sleep, 25 Clipboard := Clipboard ; Convert any copied files, HTML, or other formatted text to plain text Sleep, 25 If (StrLen(Clipboard)>=5000) { MsgBox % "Warning! You are about to paste [ " StrLen(Clipboard) " ] characters. This may take some type to type. Press WinKey + ESC to cancel" } SendInput % EscapeSpecialCharacters(Clipboard) Sleep, 25 Return } ; ; PasteClipboardAsText ; |--> Types the current clipboard's contained data, character-by-character (as if the user typed it instead of pasting it) ; PasteClipboardAsText(StringToPaste:="") { Global DebugMode SetKeyDelay, 1, -1 ; A tiny delay between each keypress is often required by anti-paste mechanisms on websites - Set the shortest delay to work around this AwaitModifierKeyup() ; Wait until all modifier keys are released Sleep 250 StringToPaste := % ((StrLen(StringToPaste)<=0)?(Clipboard):(StringToPaste)) If (StrLen(StringToPaste)>=5000) { MsgBox % "Warning! You are about to paste [ " StrLen(StringToPaste) " ] characters. This may take some type to type. Press WinKey + ESC to cancel" } Loop, Parse, % RegexConsolidateNewlines(StringToPaste) { ; DoSleep := 0 SendChar := "" If (A_LoopField == "{") { SendChar := "{" "{" "}" } Else If (A_LoopField == "}") { SendChar := "{" "}" "}" } Else If ((A_LoopField=="^")||(A_LoopField=="+")||(A_LoopField=="!")||(A_LoopField=="#")) { SendChar := "{" A_LoopField "}" ; SendRaw %A_LoopField% } Else If ((A_LoopField=="`n")||(A_LoopField=="`r")) { SendChar := "{" "`n" "}" ; DoSleep := 1 } Else { SendChar := A_LoopField } ; If (DoSleep == 1) { ; Sleep 50 ; } SendInput %SendChar% ; If (DoSleep == 1) { ; Sleep 50 ; } } Return } ; ; PasteClipboard_TextOrBinary ; |--> Displays a menu asking user if they wish to paste the clipboard as Text or Binary data (workaround for websites which block pasting into forms) ; PasteClipboard_TextOrBinary() { SetTimer, CustomMsgboxButtons_ClipboardTextOrBinary, 50 MsgBox, 3, Text or Binary, Paste the Clipboard as Text or Binary? If (A_MsgBoxResult = "Yes") { ; Paste the Text version of the Clipboard PasteClipboardAsText() } If (A_MsgBoxResult = "No") { ; Paste the Binary version of the Clipboard PasteClipboardAsBinary() } Return } CustomMsgboxButtons_ClipboardTextOrBinary: If (WinExist("Text or Binary")=0) { Return ; Continue waiting for the "Clipboard or ClipboardAll" window to appear } SetTimer, CustomMsgboxButtons_ClipboardTextOrBinary, Off WinActivate ControlSetText, Button1, &Text ControlSetText, Button2, &Binary Return ; ; PrintEnv ; |--> Gets Windows Environment Vars (output to file) ; PrintEnv() { ; --- Custom Globals Global COMPUTERNAME Global USERNAME ; --- Windows Default-Globals ALLUSERSPROFILE := EnvGet("ALLUSERSPROFILE") APPDATA := EnvGet("APPDATA") COMMONPROGRAMFILES := EnvGet("COMMONPROGRAMFILES") COMPUTERNAME := EnvGet("COMPUTERNAME") HOMEDRIVE := EnvGet("HOMEDRIVE") HOMEPATH := EnvGet("HOMEPATH") LOCALAPPDATA := EnvGet("LOCALAPPDATA") LOGONSERVER := EnvGet("LOGONSERVER") PROGRAMDATA := EnvGet("PROGRAMDATA") ; PROGRAMFILES := EnvGet("PROGRAMFILES") PUBLIC := EnvGet("PUBLIC") SYSTEMDRIVE := EnvGet("SYSTEMDRIVE") SYSTEMROOT := EnvGet("SYSTEMROOT") TEMP := EnvGet("TEMP") TMP := EnvGet("TMP") USERDOMAIN := EnvGet("USERDOMAIN") USERNAME := EnvGet("USERNAME") USERPROFILE := EnvGet("USERPROFILE") WINDIR := EnvGet("WINDIR") Viewport_TopLeft_Coords_X := SysGet(76) ; SM_XVIRTUALSCREEN Viewport_TopLeft_Coords_Y := SysGet(77) ; SM_YVIRTUALSCREEN Viewport_Width := SysGet(78) ; SM_CXVIRTUALSCREEN Viewport_Height := SysGet(79) ; SM_CYVIRTUALSCREEN Monitor_Count := SysGet(80) ; SM_CMONITORS ; ; *** Windows Env-Vars *** ; ; ALLUSERSPROFILE %ALLUSERSPROFILE% ; APPDATA %APPDATA% ; COMMONPROGRAMFILES %COMMONPROGRAMFILES% ; COMPUTERNAME %COMPUTERNAME% ; HOMEDRIVE %HOMEDRIVE% ; HOMEPATH %HOMEPATH% ; LOCALAPPDATA %LOCALAPPDATA% ; LOGONSERVER %LOGONSERVER% ; PROGRAMDATA %PROGRAMDATA% ; PROGRAMFILES %PROGRAMFILES% ; PUBLIC %PUBLIC% ; SYSTEMDRIVE %SYSTEMDRIVE% ; SYSTEMROOT %SYSTEMROOT% ; TEMP %TEMP% ; TMP %TMP% ; USERDOMAIN %USERDOMAIN% ; USERNAME %USERNAME% ; USERPROFILE %USERPROFILE% ; WINDIR %WINDIR% ; ; KnownWinEnvVars := ; https://lexikos.github.io/v2/docs/Variables.htm#CoordMode Msgbox, (LTrim ----------------------------- AHK Env-Vars ----------------------------- A_AhkPath: %A_AhkPath% A_AhkVersion: %A_AhkVersion% A_AutoTrim: %A_AutoTrim% A_ControlDelay: %A_ControlDelay% A_CoordModeCaret: %A_CoordModeCaret% A_CoordModeMenu: %A_CoordModeMenu% A_CoordModeMouse: %A_CoordModeMouse% A_CoordModePixel: %A_CoordModePixel% A_CoordModeToolTip: %A_CoordModeToolTip% A_Cursor: %A_Cursor% A_DefaultGui: %A_DefaultGui% A_DefaultListView: %A_DefaultListView% A_DefaultMouseSpeed: %A_DefaultMouseSpeed% A_DefaultTreeVie: %A_DefaultTreeView% A_IconNumber: %A_IconNumber% A_IconTip: %A_IconTip% A_IsCompiled: %A_IsCompiled% A_IsUnicode: %A_IsUnicode% A_KeyDelay: %A_KeyDelay% A_KeyDuration: %A_KeyDuration% A_LineNumber: %A_LineNumber% A_MouseDelay: %A_MouseDelay% A_MSec: %A_MSec% A_Now: %A_Now% A_NowUTC: %A_NowUTC% A_PriorHotkey: %A_PriorHotkey% A_ScriptDir: %A_ScriptDir% A_ScriptFullPath: %A_ScriptFullPath% A_ScriptName: %A_ScriptName% A_SendLevel: %A_SendLevel% A_SendMode: %A_SendMode% A_StringCaseSense: %A_StringCaseSense% A_ThisFunc: %A_ThisFunc% A_ThisLabel: %A_ThisLabel% A_ThisHotkey: %A_ThisHotkey% A_TickCount: %A_TickCount% A_TimeSincePriorHotkey: %A_TimeSincePriorHotkey% A_WinDelay: %A_WinDelay% A_WorkingDir: %A_WorkingDir% ----------------------------- Windows Env-Vars ----------------------------- A_AppData: %A_AppData% A_AppDataCommon %A_AppDataCommon% A_ComputerName: %A_ComputerName% A_ComSpec: %A_ComSpec% A_Desktop: %A_Desktop% A_DesktopCommon %A_DesktopCommon% A_IPAddress1: %A_IPAddress1% A_Is64bitOS: %A_Is64bitOS% A_IsAdmin: %A_IsAdmin% A_Language: %A_Language% A_MyDocuments: %A_MyDocuments% A_OSVersion: %A_OSVersion% A_ProgramFiles: %A_ProgramFiles% A_Programs: %A_Programs% A_ProgramsCommon %A_ProgramsCommon% A_PtrSize: %A_PtrSize% A_ScreenDPI: %A_ScreenDPI% A_ScreenHeight: %A_ScreenHeight% A_ScreenWidth: %A_ScreenWidth% A_StartMenu: %A_StartMenu% A_StartMenuCommon %A_StartMenuCommon% A_Startup: %A_Startup% A_Temp: %A_Temp% A_UserName: %A_UserName% A_WinDir: %A_WinDir% ----------------------------- SysGet Values ----------------------------- 76 - Viewport_TopLeft_Coords_X := %Viewport_TopLeft_Coords_X% 77 - Viewport_TopLeft_Coords_Y := %Viewport_TopLeft_Coords_Y% 78 - Viewport_Width := %Viewport_Width% 79 - Viewport_Height := %Viewport_Height% 80 - Monitor_Count := %Monitor_Count% -------------------------------------------------------------------------------------------- ) ; Note: For some reason, adding newlines to MsgBox makes it not wrap text ; ; FormatTime,TIMESTAMP,,yyyyMMddTHHmmss ; Logfile_EnvVars := A_Desktop "\WindowsEnvVars-" COMPUTERNAME "-" USERNAME ".log" ; Logfile_EnvVars_Timestamp := A_Desktop "\WindowsEnvVars-" COMPUTERNAME "-" USERNAME "-" TIMESTAMP ".log" ; ; FileAppend, %KnownWinEnvVars%, %Logfile_EnvVars_Timestamp% ; Run, Notepad "%Logfile_EnvVars_Timestamp%" ; Return } ; ; ProcessExist (proxy-function for GetPID(...)) ; |--> Returns True if process IS found ; |--> Returns False if process is NOT found ; ProcessExist(ProcName) { Return (GetPID(ProcName)>0) ? True : False } ; ; RegexConsolidateNewlines ; |--> The characters '`n' & '`r' are interpreted the same (by Windows) when AHK 'types' them in (sends them). ; RegexConsolidateNewlines(StringToConsolidate:="") { Return RegExReplace(StringToConsolidate,"\r\n?|\n\r?","`n") } ; ; RemoveSplashText ; |--> Removes any SplashText found ; RemoveSplashText() { ; SplashTextOff Return } ; ; RemoveToolTip ; |--> Removes any Tooltips found ; RemoveToolTip() { ToolTip Return } ; ; RunExe_NON_Admin ; |--> Opens target program without administrative rights (by using a Scheduled Task de-escalation workaround) ; RunExe_NON_Admin(FullPath_RunExe, Exe_Args:="") { If (DebugMode == 1) { TrayTip, AHK, (LTrim Opening NON-Admin version of Exe: "%Execute%"... ) ; Toast Notification } Semicolon := ";" Add_Args := "" If (Exe_Args != "") { Add_Args := " -Argument (Write-Output %Exe_Args%)" } ; Prep the output powershell script's contents (which will get nested into a vbs script so that it can run silently via wscript.exe) PowerShell_Script_Block := " ( If ([Boolean](1)) { SV TEMP_Execute '%FullPath_RunExe%'%Semicolon% SV TEMP_Name (Get-Date -UFormat `%s)%Semicolon% SV TEMP_Action (New-ScheduledTaskAction -Execute ((GV TEMP_Execute).Value)%Add_Args%)%Semicolon% SV TEMP_Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date))%Semicolon% Register-ScheduledTask -Action ((GV TEMP_Action).Value) -Trigger ((GV TEMP_Trigger).Value) -TaskName ((GV TEMP_Name).Value)%Semicolon% Start-ScheduledTask -TaskName ((GV TEMP_Name).Value)%Semicolon% Start-Sleep -Seconds 1%Semicolon% Unregister-ScheduledTask -TaskName ((GV TEMP_Name).Value) -Confirm:([Boolean](0))%Semicolon% } )" PowerShell_Script_Block := StrReplace(StrReplace(PowerShell_Script_Block,"`t",""),"`n"," ") ; Prep the output VBS script's contents VbsScript_Contents := % "CreateObject( `"WScript.Shell`" ).Run `"PowerShell -Command `"`"" PowerShell_Script_Block "`"`" `", 0, True" ; Build the output directory FullPath_RunNonAdmin_Dirname := % A_Temp "\" A_ScriptName "\" A_ThisFunc ; Build the output filename SplitPath %FullPath_RunExe%, OutFileName, OutDirname, OutExtension, OutNameNoExt, OutDrive FullPath_RunNonAdmin_VbsScript := % FullPath_RunNonAdmin_Dirname "\" OutFileName ".vbs" ; Create the VBS script file (if it doesn't already exist) If (!FileExist(FullPath_RunNonAdmin_VbsScript)) { ; Create the VBS script's directory (if it doesn't already exist) If (!FileExist(FullPath_RunNonAdmin_Dirname)) { DirCreate % FullPath_RunNonAdmin_Dirname } FileAppend, %VbsScript_Contents%, %FullPath_RunNonAdmin_VbsScript% } ; Run_PowerShellScript_NonAdmin := % "powershell.exe -WindowStyle Hidden -Command `"" PowerShell_Script_Block "`"" ; Run, %Run_PowerShellScript_NonAdmin% Run_VbsScript_NonAdmin := % "C:\Windows\System32\wscript.exe `"" FullPath_RunNonAdmin_VbsScript "`"" Run, %Run_VbsScript_NonAdmin% Return } ; ; RunWaitOne ; |--> Executes a single command through the current ComSpec (usually "cmd.exe") | https://www.autohotkey.com/docs/commands/Run.htm#StdOut ; |--> Example-call: ; MsgBox % RunWaitOne("dir " A_ScriptDir) ; RunWaitOne(CMD_Command) { WScript_Shell := ComObjCreate("WScript.Shell") Run_Command := A_ComSpec " /C `"" CMD_Command "`" " If (DebugMode == 1) { TooltipOutput := "Run_Command=[" Run_Command "]" Tooltip, %TooltipOutput% ClearTooltip(7500) } WScript_Shell_Exec := WScript_Shell.Run(Run_Command, 0, true) Return WScript_Shell_Exec } ; ; RunWaitMany ; |--> Executes multiple commands through the current ComSpec (usually "cmd.exe") | https://www.autohotkey.com/docs/commands/Run.htm#StdOut ; |--> Example-call: ; MsgBox % RunWaitMany(" ; ( ; echo Put your commands here, ; echo each one will be run, ; echo and you'll get the output. ; )") ; RunWaitMany(CMD_Commands) { WScript_Shell := ComObjCreate("WScript.Shell") ; Open cmd.exe with echoing of commands disabled WScript_Shell_Exec := WScript_Shell.Exec(ComSpec " /Q /K echo off") ; Send the commands to execute, separated by newline WScript_Shell_Exec.StdIn.WriteLine(CMD_Commands "`nexit") ; Always exit at the end! ; Read and return the output of all commands Return WScript_Shell_Exec.StdOut.ReadAll() } ; ; SendDashedLine ; |--> Output a line of dashes ; SendDashedLine(LineLength:=60) { AwaitModifierKeyup() ; Wait until all modifier keys are released SetKeyDelay, 0, -1 ; StringToType := StringRepeat("-",60) SendInput {- %LineLength%} Return } ; ; SendUnderscoreLine ; |--> Output a line of underscores ; SendUnderscoreLine(LineLength:=60) { AwaitModifierKeyup() ; Wait until all modifier keys are released SetKeyDelay, 0, -1 ; StringToType := StringRepeat("-",60) SendInput {_ %LineLength%} Return } ; ; SendHostname ; |--> Send (type) the current device's Hostname - intended to be used for quick form filling ; SendHostname() { SetKeyDelay, 0, -1 AwaitModifierKeyup() ; Wait until all modifier keys are released SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring HostName_VerbosityLevel := 0 Win_ahk_exe := WinGetProcessName("A") Win_title := WinGetTitle("A") If (Win_ahk_exe == "chrome.exe") { If ( ( WinActive("LastPass") && WinActive("Duo Security") ) || ( Win_title == "" ) ) { ; IfWinActive /// https://www.autohotkey.com/docs/commands/WinActive.htm (v1) /// https://lexikos.github.io/v2/docs/commands/WinActive.htm (v2) HostName_VerbosityLevel := 1 } } If (HostName_VerbosityLevel >= 1) { FormatTime,NowTimestamp,,yyyy-MM-dd_HH-mm-ss EchoStr := A_ComputerName " " NowTimestamp " " Win_ahk_exe Send {Blind}{Text}%EchoStr% } Else { Send {Blind}{Text}%A_ComputerName% } Return } ; ; SendPseudoRandomString ; |--> Sends/Copies a psuedo-random string of characters ; SendPseudoRandomString(CopyStringToClipboard:=1) { SpecialChar := "@" PseudoRandomString := "" PseudoRandomString := PseudoRandomString . GetRandomString(1, 0, 0, 1, 0) ; 1 Uppercase PseudoRandomString := PseudoRandomString . GetRandomString(9, 1, 1, 0, 0) ; 9 Lowercase & Numbers PseudoRandomString := PseudoRandomString . SpecialChar ; 1 Special PseudoRandomString := PseudoRandomString . GetRandomString(9, 1, 1, 0, 0) ; 9 Lowercase & Numbers PasteClipboardAsText(PseudoRandomString) If (CopyStringToClipboard == 1) { Clipboard := PseudoRandomString If (DebugMode == 1) { Text_TrayTip := "Copied string to the Clipboard`nPaste with CTRL + V" TrayTip, AHK, %Text_TrayTip% ; Toast Notification } } } ; ; SendRandomString ; |--> Sends/Copies a random string of characters ; SendRandomString(DesiredStringLength:=20, EnableNumbers:=1, EnableLowercaseLetters:=1, EnableUppercaseLetters:=0, EnableSpecialCharacters:=0, CopyStringToClipboard:=1, DoConfirmationPopup:=1) { BlockAction := 1 If (DoConfirmationPopup==0) { BlockAction := 0 } Else { MsgBox, 4,, % ( "Generate Random String (overwrites clipboard contents)?" ) If (A_MsgBoxResult = "Yes") { BlockAction := 0 } } If ( BlockAction == 0 ) { RandomString := GetRandomString(DesiredStringLength, EnableNumbers, EnableLowercaseLetters, EnableUppercaseLetters, EnableSpecialCharacters) PasteClipboardAsText(RandomString) If (CopyStringToClipboard == 1) { Clipboard := RandomString If (DebugMode == 1) { Text_TrayTip := "Copied string to the Clipboard`nPaste with CTRL + V" TrayTip, AHK, %Text_TrayTip% ; Toast Notification } } } } ; ; SendSpace ; |--> For some reason, Windows 10 doesn't like Send {Space} (as-in it 'ignores' the keypress), but happily accepts Send {SC039} as equivalent to a spacebar-press ; SendSpace() { Send {SC039} Return } ; ; ShowCursorCoordinates ; |--> Follows the mouse-cursor and displays its the X,Y coordinates (as a tooltip next to the cursor) ; ShowCursorCoordinates(FollowDuration_Seconds:=10) { PollDuration_ms := 10 Loop_Iterations := Floor((1000 * FollowDuration_Seconds) / PollDuration_ms) Loop Loop_Iterations { ; Win_ahk_exe := WinGetProcessName("A") ; ; Screen: "Coordinates are relative to the desktop (entire screen)." ; CoordMode, Mouse, Screen MouseGetPos, MouseX_Screen, MouseY_Screen Tooltip_Coords_Screen := "x" MouseX_Screen " y" MouseY_Screen " (Screen)" ; ; Window: "Coordinates are relative to the active window." ; CoordMode, Mouse, Window MouseGetPos, MouseX_Window, MouseY_Window Tooltip_Coords_Window := "x" MouseX_Window " y" MouseY_Window " (Window)" ; ; Client: "Coordinates are relative to the active window's client area, which excludes the window's title bar, menu (if it has a standard one) and borders. Client coordinates are less dependent on OS version and theme." ; CoordMode, Mouse, Client MouseGetPos, MouseX_Client, MouseY_Client Tooltip_Coords_Client := "x" MouseX_Client " y" MouseY_Client " (Client)" Tooltip, % ( Tooltip_Coords_Screen "`n" Tooltip_Coords_Window "`n" Tooltip_Coords_Client ) Sleep % ( PollDuration_ms ) } ClearTooltip(0) Return } ; ; ShowCursorPixelColor ; |--> Follows the mouse-cursor and displays the color of the pixel under it, continuously (as a tooltip next to the cursor) ; ShowCursorPixelColor(FollowDuration_Seconds:=10) { Global DebugMode CoordMode, Pixel, Screen FollowDuration_ms := (1000 * FollowDuration_Seconds) If (DebugMode == 1) { TrayTip, AHK, % ( DebugString ) ; Toast Notification OutputFile := A_Desktop "\rgblogging.txt" Logfile := FileOpen(OutputFile, "w") If (FileExist("%OutputFile%")) { FileDelete OutputFile } Logfile.write("`n") } PollDuration_ms := 10 Show_ResolvedColorName := 0 Last_MouseX := 0 Last_MouseY := 0 Last_Blue := 0 Last_Green := 0 Last_Red := 0 TickCount_BeforeLoop := A_TickCount Loop { Runtime_Net_ms := (A_TickCount-TickCount_BeforeLoop) RemainingHover_ms := (FollowDuration_ms - Runtime_Net_ms) RemainingHover_Seconds := Round((RemainingHover_ms/1000), 1) If ( RemainingHover_Seconds <= 0 ) { Break } Else { Sleep %PollDuration_ms% } ; ; Screen: "Coordinates are relative to the desktop (entire screen)." ; CoordMode, Mouse, Screen MouseGetPos, MouseX_Screen, MouseY_Screen ; ; Window: "Coordinates are relative to the active window." ; CoordMode, Mouse, Window MouseGetPos, MouseX_Window, MouseY_Window ; ; Client: "Coordinates are relative to the active window's client area, which excludes the window's title bar, menu (if it has a standard one) and borders. Client coordinates are less dependent on OS version and theme." ; CoordMode, Mouse, Client MouseGetPos, MouseX_Client, MouseY_Client Color := PixelGetColor(MouseX_Screen, MouseY_Screen) ; PixelGetColor, Color, MouseX, MouseY ColorComponent_Blue := (Color & 0xFF) ColorComponent_Green := ((Color & 0xFF00) >> 8) ColorComponent_Red := ((Color & 0xFF0000) >> 16) If (Show_ResolvedColorName == 1) { ColorDelta_BlueGreen := Abs(ColorComponent_Blue - ColorComponent_Green) ColorDelta_GreenRed := Abs(ColorComponent_Green - ColorComponent_Red) ColorDelta_BlueRed := Abs(ColorComponent_Blue - ColorComponent_Red) Color_ResolvedName := "???" If ((ColorComponent_Blue<=70) && (ColorComponent_Green<=70) && (ColorComponent_Red<=70)) { Color_ResolvedName := "Too-Dark" } Else If ((ColorDelta_GreenRed <= 10) && ((ColorComponent_Red-ColorComponent_Blue)>=20) && ((ColorComponent_Green-ColorComponent_Blue)>=15)) { Color_ResolvedName := "Yellow" } Else If (((ColorComponent_Red/ColorComponent_Green) >= 1.1) && ((ColorComponent_Red - ColorComponent_Green) >= 10) && ((ColorComponent_Red/ColorComponent_Blue) >= 1.1) && ((ColorComponent_Red - ColorComponent_Blue) >= 10) && ((ColorComponent_Blue-ColorComponent_Green) >= -5)) { Color_ResolvedName := "Magenta" } Else If ((ColorComponent_Green >= 40) && ((ColorComponent_Green - ColorComponent_Blue) >= 15) && ((ColorComponent_Green - ColorComponent_Red) >= 15) && (ColorDelta_BlueRed <= 15)) { Color_ResolvedName := "Green" } Else If (((ColorComponent_Blue/ColorComponent_Green) <= 1.35) && ((ColorComponent_Green/ColorComponent_Red) <= 1.35) && ((ColorComponent_Blue/ColorComponent_Red) <= 1.35)) { Color_ResolvedName := "White" } Else If ( (((ColorComponent_Blue-ColorComponent_Green)>=10)||((ColorComponent_Blue>=245)&&(ColorComponent_Green>=235))) && ((ColorComponent_Blue - ColorComponent_Red) >= 20) && ((ColorComponent_Green - ColorComponent_Red) >= 5)) { Color_ResolvedName := "Blue" } } TooltipOutput := "" TooltipOutput := TooltipOutput "Mouse Coords:" "`n" TooltipOutput := TooltipOutput " x" MouseX_Screen " y" MouseY_Screen " (Screen)" "`n" TooltipOutput := TooltipOutput " x" MouseX_Window " y" MouseY_Window " (Window)" "`n" TooltipOutput := TooltipOutput " x" MouseX_Client " y" MouseY_Client " (Client)" "`n" TooltipOutput := TooltipOutput "`n" TooltipOutput := TooltipOutput "Pixel Color:" "`n" TooltipOutput := TooltipOutput " " Color " (Hex)" "`n" TooltipOutput := TooltipOutput " rgb(" ColorComponent_Red "," ColorComponent_Green "," ColorComponent_Blue ")" "`n" TooltipOutput := TooltipOutput "`n" If (Show_ResolvedColorName == 1) { TooltipOutput := TooltipOutput "Color_ResolvedName=[" Color_ResolvedName "] " "`n" } If (DebugMode == 1) { TooltipOutput := TooltipOutput "OutputFile=[" OutputFile "] " "`n" } If ((Last_MouseX != MouseX_Screen) || (Last_MouseY != MouseY_Screen) || (Last_Blue != ColorComponent_Blue) || (Last_Green != ColorComponent_Green) || (Last_Red != ColorComponent_Red)) { Tooltip, %TooltipOutput% ; Only perform updates if any discernible change is detected (amongst colors & mouse position values) If (DebugMode == 1) { LogfileOutput := StrReplace(TooltipOutput,"`n"," ") Logfile.write("%LogfileOutput%`n") } Last_MouseX := MouseX_Screen Last_MouseY := MouseY_Screen Last_Blue := ColorComponent_Blue Last_Green := ColorComponent_Green Last_Red := ColorComponent_Red } } If (DebugMode == 1) { Logfile.close() Sleep 250 Run, Notepad "%OutputFile%" } ClearTooltip(0) Return } ; ; ShowTooltip ; |--> Show a tooltip & make said tooltip follow the mouse around for a given duration ; ShowTooltip(TextToolTip:="", LoopDuration_ms:=5000) { StartMilliseconds := A_TickCount Loop { ToolTip, %TextToolTip% LoopingForMilliseconds := (A_TickCount-StartMilliseconds) If (LoopingForMilliseconds > LoopDuration_ms) { Break } Else { Sleep 50 } } ClearTooltip(0) } ; ; ShowVolumeLevel ; |--> Show a tooltip with the volume as an integer, as well as filled-bars around it to intuitively show the volume, as well as a mute icon around the integer if muted ; ShowVolumeLevel() { CoordMode, Mouse, Screen CoordMode, ToolTip, Screen Icon_MutedSpeaker := "🔇" Icon_SpeakerLowVolume := "🔈" Icon_SpeakerMediumVolume := "🔉" Icon_SpeakerHighVolume := "🔊" Icon_VolumeFilled := "⬛️" Icon_VolumeBlanks := "⬜️" ; Get the volume & mute current-settings SoundGet, NewVolumeLevel SoundGet, MasterMute, , MUTE ; Final volume level NewVolumeLevel := Round( NewVolumeLevel ) NewVolumeLevelPercentage := NewVolumeLevel "`%" ; Build the volume-bars (out-of dingbats/utf8+ icons) Total_IconCount_MaxVolume := 20 IconCount_TopBot_Filled := Round( ( NewVolumeLevel / 100 ) * Total_IconCount_MaxVolume) IconCount_TopBot_Blanks := Total_IconCount_MaxVolume - IconCount_TopBot_Filled DisplayedIcons_TopBot_Filled := StringRepeat( Icon_VolumeFilled, IconCount_TopBot_Filled ) DisplayedIcons_TopBot_Blanks := StringRepeat( Icon_VolumeBlanks, IconCount_TopBot_Blanks ) VolumeBars_TopBot := DisplayedIcons_TopBot_Filled DisplayedIcons_TopBot_Blanks IconCount_Middle_Filled := Round( ( NewVolumeLevel / 100 ) * Total_IconCount_MaxVolume) - 4 IconCount_Middle_Blanks := Total_IconCount_MaxVolume - IconCount_Middle_Filled DisplayedIcons_Middle_Filled := StringRepeat( Icon_VolumeFilled, IconCount_Middle_Filled ) DisplayedIcons_Middle_Blanks := StringRepeat( Icon_VolumeBlanks, IconCount_Middle_Blanks ) VolumeBars_Middle := DisplayedIcons_Middle_Filled DisplayedIcons_Middle_Blanks TrimCount_TopBot := Round( StrLen( VolumeBars_TopBot ) / 2 ) TrimCount_Middle := Round( StrLen( VolumeBars_Middle ) / 2 ) Echo_TopBot_LeftHalf := RTrim(SubStr(VolumeBars_TopBot, 1, (StrLen(VolumeBars_TopBot)-TrimCount_TopBot) )) Echo_TopBot_RightHalf := RTrim(SubStr(VolumeBars_TopBot, TrimCount_TopBot, StrLen(VolumeBars_TopBot))) Echo_TopBot_LeftHalf := Icon_SpeakerMediumVolume A_Space A_Space A_Space Echo_TopBot_LeftHalf Echo_TopBot_RightHalf := Echo_TopBot_RightHalf A_Space A_Space Icon_SpeakerHighVolume Echo_Middle_LeftHalf := Echo_TopBot_LeftHalf Echo_Middle_RightHalf := Echo_TopBot_RightHalf IconSlice_Middle_EachSide := 3 Mute_AddSpaces := 2 Echo_Middle_LeftHalf := SubStr( Echo_TopBot_LeftHalf, 1, ( -1 * IconSlice_Middle_EachSide * StrLen( Icon_VolumeFilled )) ) Echo_Middle_RightHalf := SubStr( Echo_TopBot_RightHalf, ( IconSlice_Middle_EachSide * StrLen( Icon_VolumeFilled )) ) ; Show mute status next to the integer volume level ; |--> Replace mute-icon w/ whitespace if un-muted Mute_StatusIcon := ( ( MasterMute == "On" ) ? ( Icon_MutedSpeaker ) : ( StringRepeat( A_Space , 4 ) ) ) Mute_LSpaces := ( Round( Mute_AddSpaces / 2 ) ) Mute_RSpaces := ( Mute_AddSpaces - Mute_LSpaces ) Mute_Padding := StringRepeat( A_Space , Mute_LSpaces ) Mute_StatusIcon StringRepeat( A_Space , Mute_RSpaces ) If ( NewVolumeLevel == 100 ) { ; Mute_AddSpaces := Mute_AddSpaces + 0 Echo_Middle_Center := Mute_Padding NewVolumeLevel Mute_Padding } Else If ( NewVolumeLevel >= 10 ) { ; Mute_AddSpaces := Mute_AddSpaces + 1 Echo_Middle_Center := Mute_Padding A_Space A_Space NewVolumeLevel Mute_Padding } Else { ; Mute_AddSpaces := Mute_AddSpaces + 2 Echo_Middle_Center := Mute_Padding A_Space A_Space NewVolumeLevel A_Space A_Space Mute_Padding } Echo_TopBot_Center := StringRepeat( A_Space , 0 ) Echo_Tooltip := "" Echo_Tooltip := Echo_Tooltip Echo_TopBot_LeftHalf Echo_TopBot_Center Echo_TopBot_RightHalf "`n" Echo_Tooltip := Echo_Tooltip Echo_Middle_LeftHalf Echo_Middle_Center Echo_Middle_RightHalf "`n" Echo_Tooltip := Echo_Tooltip Echo_TopBot_LeftHalf Echo_TopBot_Center Echo_TopBot_RightHalf ; ------------------------------ ; End of text-formatting calculations ; Start of windows-placement calculations ; ------------------------------ ToolTip_Width := 254 ToolTip_Height := 50 StartMenu_Height := 40 ToolTip_XPos := 50 ; Fallback/default values ToolTip_YPos := 50 ; Fallback/default values ; ------------------------------ MouseGetPos, MouseX, MouseY ; Docs: "Check if the specified monitor exists and optionally retrieve the bounding coordinates of its working area" - https://lexikos.github.io/v2/docs/commands/MonitorGetWorkArea.htm Loop % MonitorGetCount() { MonitorGetWorkArea(A_Index, EachMonitor_LeftCoord, EachMonitor_TopCoord, EachMonitor_RightCoord, EachMonitor_BottomCoord) ; Determine if the current iteration's monitor is the destination monitor MoveTo_ThisMonitor := False ; Determine if the center of target window is currently located within the bounds of this monitor's work area If ((MouseX >= EachMonitor_LeftCoord) && (MouseX <= EachMonitor_RightCoord)) { If ((MouseY >= EachMonitor_TopCoord) && (MouseY <= EachMonitor_BottomCoord)) { ; Mouse cursor is on this monitor EachMonitor_Number := A_Index EachMonitor_Width := (EachMonitor_RightCoord-EachMonitor_LeftCoord) EachMonitor_Height := (EachMonitor_BottomCoord-EachMonitor_TopCoord) ToolTip_XPos := Round(EachMonitor_LeftCoord+((EachMonitor_Width-ToolTip_Width)/2)) ToolTip_YPos := Round(EachMonitor_Height-StartMenu_Height-(ToolTip_Height*2)) ; ToolTip_YPos:=Round((EachMonitor_Height-ToolTip_Height-StartMenu_Height+39)*(1-(NewVolumeLevel/100))) Break } } } ToolTip, %Echo_Tooltip%, %ToolTip_XPos%, %ToolTip_YPos% ClearTooltip(750) Return } ; ; ShowWindowTitles ; |--> Lists all window-titles (in current user's environment) ; ShowWindowTitles() { Gui, WinTitles:Default Gui, Add, ListView, r50 w1000 gShowWindowTitles_OnDoubleClick_GuiDestroy_WinTitles, WindowTitle Window := WinGetList("A") Loop Window { Id:=Window%A_Index% WinGetTitle, TVar , % "ahk_id " Id If (Tvar != "") { LV_Add("", TVar) Window%A_Index%:=TVar ;use this if you want an array tList.=TVar "`n" ;use this if you just want the list } } ; Gui, Add, Text,, %tList% Gui, Show ; MsgBox %tList% Return } ; ; ShowWindowTitles_OnDoubleClick_GuiDestroy_WinTitles ; |--> Sub-Function of "ShowWindowTitles()" ; ShowWindowTitles_OnDoubleClick_GuiDestroy_WinTitles() { If (A_GuiEvent = "DoubleClick") { Gui, WinTitles:Default Gui, Destroy } Return } ; ; SpaceUp_Loop ; |--> Designed for Windows Task Scheduler to quickly show open all tasks on the main page, which can then be sorted (but only for the ones that've been opened) ; SpaceUp_Loop(LoopIterations) { Loop LoopIterations { Sleep 500 Send {SC039} SendSpace() Sleep 500 Send {Up} } Return } ; ; StringRepeat ; |--> Repeat a string a given number of times ; StringRepeat(StrToRepeat, Multiplier) { ReturnedVal := "" If (Multiplier > 0) { Loop { If (A_Index > Multiplier) { Break } ReturnedVal .= StrToRepeat } } Return ReturnedVal } ; ; StrLen_Max ; |--> Compare two strings - return the longer string (whichever has more characters in it) ; StrLen_Max(Str_1, Str_2) { ; StrLen_LongestString := 0 ; If ( StrLen(Str_1) > StrLen(Str_2) ) { ; StrLen_LongestString := StrLen(Str_1) ; } Else { ; StrLen_LongestString := StrLen(Str_2) ; } ; Return StrLen_LongestString Return ( (StrLen(Str_1)>StrLen(Str_2)) ? (Str_1) : (Str_2) ) } ; ; StrLenUnicode ; |--> Get String-Length for unicode string(s)? (Need better description) ; StrLenUnicode(data) { RegExReplace(data, "s).", "", i) Return i } ; ; TabSpace_Loop ; |--> Designed for Samsung SmartThings' Web-IDE where (sometimes) multiple hundreds of checkboxes need to be selected individually to update from a Git repo ; TabSpace_Loop(LoopIterations) { Loop LoopIterations { Send {Tab} Sleep 10 Send {Space} Sleep 10 } Return } ; ; TempFile ; |--> Creates a temporary file with a timestamp (down to the millisecond) based filename ; |--> Returns a string-value containing the fullpath of the temporary file (which was just created) ; TempFile() { TempFile_Dirname := A_Temp "\AutoHotkey\" If (!FileExist("%TempFile_Dirname%")) { DirCreate "%TempFile_Dirname%" } TempFile_Basename := A_Now "." A_MSec TempFile_Fullpath := TempFile_Dirname TempFile_Basename Return %TempFile_Fullpath% } ; ; WinGet_ahk_id ; | ; |--> Determines target process (exe)'s [ unique ID (e.g. 'HWND', which is short for "handle to window") ] ; |--> Intended to transparently inspect THROUGH "ApplicationFrameHost.exe" (which runs Windows 10 'apps' (applications)) ; | ; |--> Ex) Win_ahk_id := WinGet_ahk_id("A") ; WinGet_ahk_id(WinTitle) { Win_ahk_exe := WinGetProcessName(WinTitle) If (Win_ahk_exe = "ApplicationFrameHost.exe") { ControlGet, Win_ahk_id, Hwnd,, Windows.UI.Core.CoreWindow1, %WinTitle% ; Win_ahk_id := ControlGetHwnd("Windows.UI.Core.CoreWindow1", "A") } Else { Win_ahk_id := WinGetID(WinTitle) } Return Win_ahk_id } ; ; WinGet_is_win10_app ; | ; |--> Determines if target-app is running in "ApplicationFrameHost.exe" (which runs Windows 10 'apps' (applications)) ; | ; |--> Ex) Win_is_win10_app := WinGet_is_win10_app("A") ; WinGet_is_win10_app(WinTitle) { Win_ahk_exe := WinGetProcessName(WinTitle) Win_is_win10_app := 0 If (Win_ahk_exe = "ApplicationFrameHost.exe") { Win_is_win10_app := 1 } Return Win_is_win10_app } ; ; WinGet_size_state ; | ; |--> Returns "Minimized", "Restored", or "Maximized" depending on the value returned from WinGetMinMax ; | ; |--> Ex) Win_is_win10_app := WinGet_is_win10_app("A") ; WinGet_size_state(WinTitle,WinText:="") { Win_MinMaxState := WinGetMinMax(WinTitle,WinText) Win_size_state := "" If (Win_MinMaxState == 0) { Win_size_state := "restored" } Else If (Win_MinMaxState == -1) { Win_size_state := "minimized" } Else If (Win_MinMaxState == 1) { Win_size_state := "maximized" } Return Win_size_state } ; ; Win_ToggleRestoreMaximize ; |--> Toggle target window between "Maximized" and "Non-Maximized" (or "Restored") states ; Win_ToggleRestoreMaximize(WinTitle:="A") { Global DebugMode Win_MinMaxState := WinGetMinMax(WinTitle) DebugString := "Win_MinMaxState=[ %Win_MinMaxState% ]" If ("%Win_MinMaxState%" = "") { ; ??? Window-state not pulled as-intended WinMaximize(WinTitle) DebugString := DebugString "`n" " |--> Do WinMaximize" } Else { If (Win_MinMaxState == 0) { ; 0: The window is restored (neither minimized nor maximized) - do WinMaximize to maximize it WinMaximize(WinTitle) DebugString := DebugString "`n" " |--> Do WinMaximize" } Else If (Win_MinMaxState == -1) { ; -1: The window is minimized - do WinRestore to unminimize it WinRestore(WinTitle) DebugString := DebugString "`n" " |--> Do WinRestore" } Else If (Win_MinMaxState == 1) { ; 1: The window is maximized - do WinRestore to unmaximize it WinRestore(WinTitle) DebugString := DebugString "`n" " |--> Do WinRestore" } Else { ; Fallthrough-catch WinMaximize(WinTitle) DebugString := DebugString "`n" " |--> Do WinMaximize" } } If (DebugMode == 1) { TrayTip, AHK, % ( DebugString ) ; Toast Notification } Return } ; ; XBox_DownloadDelete_GameClips ; |--> Win10 Download & Delete Recordings via XBox Win10 App ; XBox_DownloadDelete_GameClips() { Global DebugMode CoordMode, Mouse, Screen SetControlDelay, -1 SetDefaultMouseSpeed, 0 SetKeyDelay, 0, -1 SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring AwaitModifierKeyup() ; Wait until all modifier keys are released ; ------------------------------------------------------------ ; ; Runtime Options ; MaxFilesToDownload := 0 ; 0 = Unlimited ; MaxFilesToDownload := 2 Download_GameClips := 1 ; Download Game clips? YES ; Download_GameClips := 0 ; Download Game clips? NO ; Download_Screenshots := 1 ; Download Screenshots? YES Download_Screenshots := 0 ; Download Screenshots? NO ; ------------------------------------------------------------ WinTitle := "Xbox Console Companion" ; Win_ahk_id := WinGetID("A") Win_ahk_id := WinGetID(WinTitle) Win_title := WinGetTitle("ahk_id %Win_ahk_id%") Win_ahk_class := WinGetClass("ahk_id %Win_ahk_id%") Win_ahk_exe := WinGetProcessName("ahk_id %Win_ahk_id%") Win_ahk_pid := WinGetPID("ahk_id %Win_ahk_id%") Win_size_state := WinGet_size_state("ahk_id %Win_ahk_id%") Win10_ahk_id := WinGet_ahk_id(WinTitle) Win10_title := WinGetTitle("ahk_id %Win10_ahk_id%") Win10_ahk_class := WinGetClass("ahk_id %Win10_ahk_id%") Win10_ahk_pid := WinGetPID("ahk_id %Win10_ahk_id%") Win10_ahk_exe := WinGetProcessName("ahk_id %Win10_ahk_id%") Win_MinMaxState := WinGetMinMax("ahk_id %Win_ahk_id%") Tooltip_Header := A_ThisFunc "`n" "----------" TickCount_RuntimeStart := A_TickCount MediaFiles_Processed := 0 Color_Buffering_GameClips := "0x2E2E2E" Color_Buffering_Screenshots := "0x171717" Color_DL_Button_NotDownloading := "0x171717" Color_DL_Button_Downloading := "0x595758" Color_Loaded_CapturesPage := "0xFFFFFF" Color_Loaded_OnXboxLiveTab := "0xFFFFFF" Loop 2 { If ( A_Index == 1 ) { Download_MediaType := "Game clips" ; Download "Game clips" } Else { Download_MediaType := "Screenshots" ; Download "Screenshots" } If ((Download_MediaType == "Game clips") && (Download_GameClips == 0)) { ; ; If option "Download_GameClips" is disabled (set to 0), skip downloading/deleting Xbox Live Game clips ; Continue } Else If ((Download_MediaType == "Screenshots") && (Download_Screenshots == 0)) { ; ; If option "Download_Screenshots" is disabled (set to 0), skip downloading/deleting Xbox Live Screenshots ; Continue } Else { Tooltip_StartupJobs := Tooltip_Header If (Download_MediaType == "Game clips") { WaitDuration_MediaType := 1.5 } Else { WaitDuration_MediaType := 1.0 } Loop 4 { Tooltip_NewStats := "" If (A_Index == 1) { ; ------------------------------ ; ; Resizing 'Xbox Console Companion' Window ; Tooltip_NewStats := ( "Prepping Xbox window..." ) Tooltip, % ( Tooltip_StartupJobs "`n" Tooltip_NewStats ), 1, 1 WinActivate("ahk_id %Win_ahk_id%") Sleep 500 If (Win_size_state != "restored") { WinActivate("ahk_id %Win_ahk_id%") WinRestore("ahk_id %Win_ahk_id%") Sleep 1000 } WinActivate("ahk_id %Win_ahk_id%") ; ; Move the window to specified x/y position and resize it to have specified width/height ; WinMove("ahk_id %Win_ahk_id%",, -7, 0, 1280, 800) Sleep 500 Tooltip_StartupJobs := ( Tooltip_StartupJobs "`n" Tooltip_NewStats " Done" ) Sleep 500 } Else If (A_Index == 2) { ; ------------------------------ ; ; Loading 'Captures' tab ... ; TickCount_LoadCaptures := A_TickCount WinActivate("ahk_id %Win_ahk_id%") MouseClick, Left, 23, 314 ; Load 'Captures' tab (left-panel) Sleep 500 Loop { Sleep 100 WaitDuration_Seconds := Round(((A_TickCount-TickCount_LoadCaptures)/1000), 1) Tooltip_NewStats := ( "Loading 'Captures' (tab): " WaitDuration_Seconds "s ..." ) Tooltip, % ( Tooltip_StartupJobs "`n" Tooltip_NewStats ), 1, 1 If ( WaitDuration_Seconds > 0.5 ) { ; Wait a minimum short-duration per download WinActivate("ahk_id %Win_ahk_id%") ; ; Check the color of each pixel in a 2-D horizontal line which passes over the "On This PC" and "On Xbox Live" tab name texts ; |--> Keep checking until a white color (0xFFFFFF) is found somewhere along said coordinate line (which denotes the page has loaded) ; If (PixelSearch(Px, Py, 61, 140, 280, 140, Color_Loaded_CapturesPage, 0)) { Tooltip_StartupJobs := ( Tooltip_StartupJobs "`n" Tooltip_NewStats " Done" ) Tooltip, % ( Tooltip_StartupJobs ), 1, 1 Sleep 500 Break } Else { Continue } } } } Else If (A_Index == 3) { ; ------------------------------ ; ; Loading 'On Xbox Live' (tab)... ; TickCount_LoadXboxLive := A_TickCount WinActivate("ahk_id %Win_ahk_id%") MouseClick, Left, 220, 138 ; Load 'On Xbox Live' tab (top-option within 'Captures') Sleep 500 Loop { Sleep 100 WaitDuration_Seconds := Round(((A_TickCount-TickCount_LoadXboxLive)/1000), 1) Tooltip_NewStats := ( "Loading 'On Xbox Live' (tab): " WaitDuration_Seconds "s ..." ) Tooltip, % ( Tooltip_StartupJobs "`n" Tooltip_NewStats ), 1, 1 If ( WaitDuration_Seconds > 0.5 ) { ; Wait a minimum short-duration per download ; ; Check the color of each pixel in a 2-D horizontal line which passes over the "By date" and "Everything" dropdown texts ; |--> Keep checking until a white color (0xFFFFFF) is found somewhere along said coordinate line (which denotes the tab has loaded) ; WinActivate("ahk_id %Win_ahk_id%") If ( (PixelSearch(Px, Py, 61, 180, 280, 180, Color_Loaded_OnXboxLiveTab, 0)) || (WaitDuration_Seconds > 20) ) { Tooltip_StartupJobs := ( Tooltip_StartupJobs "`n" Tooltip_NewStats " Done" ) Tooltip, % ( Tooltip_StartupJobs ), 1, 1 Sleep 500 Break } Else { Continue } } } } Else If (A_Index == 4) { If (Download_MediaType == "Game clips") { ; ------------------------------ ; ; Loading 'Game clips' (filter)... ; Tooltip_NewStats := ( "Showing 'Game clips' (filter) ..." ) Tooltip, % ( Tooltip_StartupJobs "`n" Tooltip_NewStats ), 1, 1 WinActivate("ahk_id %Win_ahk_id%") MouseClick, Left, 221, 181 ; Show 'Game clips', only - (under the "Everything v" dropdown/filter - second option from the top) Sleep 500 WinActivate("ahk_id %Win_ahk_id%") Send {Up} Sleep 250 WinActivate("ahk_id %Win_ahk_id%") Send {Up} Sleep 250 WinActivate("ahk_id %Win_ahk_id%") Send {Down} Sleep 250 WinActivate("ahk_id %Win_ahk_id%") Send {Enter} Tooltip_StartupJobs := ( Tooltip_StartupJobs "`n" Tooltip_NewStats " Done" ) Tooltip, % ( Tooltip_StartupJobs ), 1, 1 Sleep 1000 } Else { ; ------------------------------ ; ; Loading 'Screenshots' (filter)... ; Tooltip_NewStats := ( "Showing 'Screenshots' (filter) ..." ) Tooltip, % ( Tooltip_StartupJobs "`n" Tooltip_NewStats ), 1, 1 WinActivate("ahk_id %Win_ahk_id%") MouseClick, Left, 221, 181 ; Show 'Screeshots', only - (under the "Everything v" dropdown/filter - bottom option) Sleep 500 WinActivate("ahk_id %Win_ahk_id%") Send {Down} Sleep 250 WinActivate("ahk_id %Win_ahk_id%") Send {Down} Sleep 250 WinActivate("ahk_id %Win_ahk_id%") Send {Enter} Tooltip_StartupJobs := ( Tooltip_StartupJobs "`n" Tooltip_NewStats " Done" ) Tooltip, % ( Tooltip_StartupJobs ), 1, 1 Sleep 1000 } } } Loop { Tooltip_EachFile_Stats := Tooltip_Header Tooltip_EachFile_Stats := Tooltip_EachFile_Stats "`n" "Net " Download_MediaType " processed: " MediaFiles_Processed Total_RuntimeDuration_Seconds := Round(((A_TickCount-TickCount_RuntimeStart)/1000), 1) Tooltip_EachFile_Stats := Tooltip_EachFile_Stats "`n" "Net Runtime Duration: " Total_RuntimeDuration_Seconds "s" MediaFile_Iteration := A_Index TickCount_FileExists := A_TickCount NextDownloadExists_Passed := 0 Buffer_Passed := 0 Download_Passed := 0 ; ------------------------------ ; ; Processing File #x / y ; If (MaxFilesToDownload > 0) { ; ; If option "MaxFilesToDownload" is set no a non-zero value, use its value as the maximum number of files to be downloaded ; Tooltip_EachFile_Stats := Tooltip_EachFile_Stats "`n" "Processing File # " MediaFile_Iteration "/" MaxFilesToDownload ":" If (MediaFile_Iteration >= MaxFilesToDownload) { Break } } Else { Tooltip_EachFile_Stats := Tooltip_EachFile_Stats "`n" "Processing File # " MediaFile_Iteration ":" } ; ------------------------------ ; ; File-check duration ... ; Loop { Sleep 100 WaitDuration_Seconds := Round(((A_TickCount-TickCount_FileExists)/1000), 1) Tooltip_NewStats := ( "File-check duration: " WaitDuration_Seconds "s ..." ) Tooltip, % ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats ), 1, 1 If ( WaitDuration_Seconds > WaitDuration_MediaType ) { ; Wait a minimum short-duration per download WinActivate("ahk_id %Win_ahk_id%") ; ; Check the color of each pixel in a 2-D horizontal line which passes over the top Game clip / Screenshot's filename text ; |--> Keep checking until a white color (0xFFFFFF) is found somewhere along said coordinate line (which denotes the file line item has become selectable) ; If ( PixelSearch(Px, Py, 165, 280, 355, 280, 0xFFFFFF, 43) ) { NextDownloadExists_Passed := 1 Tooltip_EachFile_Stats := ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats " Done" ) Tooltip, % ( Tooltip_EachFile_Stats ), 1, 1 Break } Else { If (WaitDuration_Seconds > 10) { ; ; Top row-item (filename) not found - Assume no more files exist ; NextDownloadExists_Passed := 0 Tooltip_EachFile_Stats := ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats " Not found" ) Tooltip, % ( Tooltip_EachFile_Stats ), 1, 1 Break } Else { Continue } } } } ; ------------------------------ ; ; Buffering... ; If ( NextDownloadExists_Passed == 1 ) { TickCount_StartBuffer := A_TickCount Loop { Sleep 100 WaitDuration_Seconds := Round(((A_TickCount-TickCount_StartBuffer)/1000), 1) Tooltip_NewStats := ( "Buffer duration: " WaitDuration_Seconds "s ..." ) Tooltip, % ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats ), 1, 1 If ( WaitDuration_Seconds > WaitDuration_MediaType ) { ; Wait a minimum short-duration per download ; Check the thumbnail's 4 corners to see if they all match the gray buffering (loading) overlay's color WinActivate("ahk_id %Win_ahk_id%") Color_Thumbnail_BotLeft := PixelGetColor(425, 470) Color_Thumbnail_TopLeft := PixelGetColor(425, 215) Color_Thumbnail_TopRight := PixelGetColor(900, 215) Color_Thumbnail_BotRight := PixelGetColor(900, 470) If ((Color_Thumbnail_BotLeft == Color_Buffering_GameClips) && (Color_Thumbnail_TopLeft == Color_Buffering_GameClips) && (Color_Thumbnail_TopRight == Color_Buffering_GameClips) && (Color_Thumbnail_BotRight == Color_Buffering_GameClips)) { Continue ; Still Buffering (Game clip) } Else If ((Color_Thumbnail_BotLeft == Color_Buffering_Screenshots) && (Color_Thumbnail_TopLeft == Color_Buffering_Screenshots) && (Color_Thumbnail_TopRight == Color_Buffering_Screenshots) && (Color_Thumbnail_BotRight == Color_Buffering_Screenshots)) { Continue ; Still Buffering (Screenshot) } Else { Buffer_Passed := 1 Tooltip_EachFile_Stats := ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats " Done" ) Tooltip, % ( Tooltip_EachFile_Stats ), 1, 1 Sleep 1000 Break } } } ; ------------------------------ ; ; Downloading... ; TickCount_StartDownload := A_TickCount DownloadBtn_XPos_LeftInterior := 418 ; Same xpos for [ Game clips ] & [ Screenshots ] DownloadBtn_XPos_Center := 542 ; Same xpos for [ Game clips ] & [ Screenshots ] If (Download_MediaType == "Game clips") { DownloadBtn_YPos_Center := 772 ; Game clips } Else { DownloadBtn_YPos_Center := 730 ; Screenshots } Loop { If (A_Index == 1) { WinActivate("ahk_id %Win_ahk_id%") MouseClick, Left, %DownloadBtn_XPos_Center%, %DownloadBtn_YPos_Center% ; Click "Download" on currently-selected file } Sleep 100 WaitDuration_Seconds := Round(((A_TickCount-TickCount_StartDownload)/1000), 1) Tooltip_NewStats := ( "Download duration: " WaitDuration_Seconds "s ..." ) Tooltip, % ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats ), 1, 1 If ( WaitDuration_Seconds > WaitDuration_MediaType ) { ; Wait a minimum short-duration per download MouseMove, 0, 0 ; Check the leftmost side of the "Download" button to see if it is still downloading the current file (it turns a lighter gray, 0x595758, while downloading, compared to its base of 0x171717) WinActivate("ahk_id %Win_ahk_id%") Color_DL_Button_LeftSide := PixelGetColor(DownloadBtn_XPos_LeftInterior, DownloadBtn_YPos_Center) If (Color_DL_Button_LeftSide == Color_DL_Button_NotDownloading) { Download_Passed := 1 Tooltip_EachFile_Stats := ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats " Done" ) Tooltip, % ( Tooltip_EachFile_Stats ), 1, 1 Sleep 1500 Break } } } } ; ------------------------------ ; ; Deleting... ; If ((NextDownloadExists_Passed == 1) && (Buffer_Passed == 1) && (Download_Passed == 1)) { DeleteBtn_XPos_TrashCan := 853 ; Same xpos for [ Game clips ] & [ Screenshots ] If (Download_MediaType == "Game clips") { DeleteBtn_YPos_Center := 731 ; Game clips } Else { DeleteBtn_YPos_Center := 618 ; Screenshots } Tooltip_NewStats := "Deleting ..." Tooltip, % ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats ), 1, 1 WinActivate("ahk_id %Win_ahk_id%") MouseClick, Left, %DeleteBtn_XPos_TrashCan%, %DeleteBtn_YPos_Center% ; Click "Delete" once download has finished Sleep 1000 Tooltip_NewStats := Tooltip_NewStats " Confirming ..." Tooltip, % ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats ), 1, 1 WinActivate("ahk_id %Win_ahk_id%") MouseClick, Left, 519, 449 ; Confirm file-deletion (via "OK" button on popup) Sleep 500 Tooltip_EachFile_Stats := ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats " Done" ) Tooltip, % ( Tooltip_EachFile_Stats ), 1, 1 Sleep 1500 MediaFiles_Processed := MediaFiles_Processed + 1 } Else { Tooltip_NewStats := "Info: " If (NextDownloadExists_Passed != 1) { Tooltip_NewStats := Tooltip_NewStats "`n" "All " Download_MediaType " have been downloaded" } Else { If (Buffer_Passed != 1) { Tooltip_NewStats := Tooltip_NewStats "`n" "Error: Buffering unable to complete" } If (Download_Passed != 1) { Tooltip_NewStats := Tooltip_NewStats "`n" "Error: Download unable to complete" } } Tooltip_EachFile_Stats := ( Tooltip_EachFile_Stats "`n" Tooltip_NewStats ) Tooltip, % ( Tooltip_EachFile_Stats ), 1, 1 Sleep 2500 Break } } ; ------------------------------ ; ; Net Files Processed && Net Runtime Duration ; Tooltip_Closer_Stats := Tooltip_Header Tooltip_Closer_Stats := Tooltip_EachFile_Stats "`n" "Net Files Processed: " MediaFiles_Processed Total_RuntimeDuration_Seconds := Round(((A_TickCount-TickCount_RuntimeStart)/1000), 1) Tooltip_Closer_Stats := Tooltip_EachFile_Stats "`n" "Net Runtime Duration: " Total_RuntimeDuration_Seconds "s" Tooltip, % ( Tooltip_Closer_Stats ), 1, 1 Sleep 2000 } } If (MediaFiles_Processed > 0) { ; ; Open the timestamping script (renames files to their basename plus their metadata created-on date) ; Tooltip_Closer_Stats := Tooltip_Closer_Stats "`n" "Opening metadata-timestamper script..." Tooltip, % ( Tooltip_Closer_Stats ), 1, 1 Timestamping_Script := % ( EnvGet("USERPROFILE") "\Documents\GitHub\cloud-infrastructure/usr/local/bin/bulk_rename_based_on_media_creation_date" ) Run, Notepad "%Timestamping_Script%" Sleep 2000 ; ; Open the output-videos directory ; Tooltip_Closer_Stats := Tooltip_Closer_Stats "`n" "Opening output directory..." Tooltip, % ( Tooltip_Closer_Stats ), 1, 1 Fullpath_XboxCaptures := ( EnvGet("USERPROFILE") "\Videos\Captures" ) Run "%Fullpath_XboxCaptures%" Sleep 2000 Tooltip_Closer_Stats := ( Tooltip_Closer_Stats "`n" "Runtime complete for '" Download_MediaType "'" ) Tooltip, % ( Tooltip_Closer_Stats ), 1, 1 Sleep 2000 } ClearTooltip(10000) Return } ; ; Youtube_EditDraft_Submit ; |--> Click "Edit Draft" then "Next"*3 then "Submit" to walk Youtube videos from "Draft" to live state ; |--> !!! MAKE SURE TO FILTER TO: "Visibility: Draft" !!! ; ; Youtube_EditDraft_Submit() { Global DebugMode CoordMode, Mouse, Screen CoordMode, Pixel, Screen SetControlDelay, -1 SetDefaultMouseSpeed, 0 SetKeyDelay, 0, -1 SetTitleMatchMode, 2 ; Title must CONTAIN [ WinTitle ] as a substring AwaitModifierKeyup() ; Wait until all modifier keys are released WinTitle := "Channel content - YouTube Studio - Google Chrome" If (WinExist(WinTitle)) { ; ; !!! MAKE SURE TO FILTER TO: "Visibility: Draft" !!! ; WinActivate(WinTitle) Sleep 100 ; Move the window to specified x/y position and resize it to have specified width/height WinMove(WinTitle,, -7, 0, 1734, 1407) Loop { Tooltip_Header := "Chrome - Click 'Refresh'" Tooltip, % ( Tooltip_Header ), 1, 112 xpos := 94 ypos := 61 ControlClick, x%xpos% y%ypos%, %WinTitle% Sleep 2000 Tooltip_Header := "Youtube - Click 'Edit Draft'" Tooltip, % ( Tooltip_Header ), 1, 112 xpos := 1601 ypos := 414 xpos_rightedge := xpos + 20 Loop { Sleep 100 Color_xpos_ypos := PixelGetColor(xpos, ypos) PixelSearch_Blue1 := PixelSearch( Px, Py, xpos, ypos, xpos_rightedge, ypos, 0x065FD4, 50 ) PixelSearch_Blue2 := PixelSearch( Px, Py, xpos, ypos, xpos_rightedge, ypos, 0x196CD7, 50 ) Tooltip_Debug := ( Tooltip_Header "`n" ) Tooltip_Debug := ( Tooltip_Debug "Color_xpos_ypos=[" Color_xpos_ypos "]" "`n" ) Tooltip_Debug := ( Tooltip_Debug "PixelSearch_Blue1=[" PixelSearch_Blue1 "]" "`n" ) Tooltip_Debug := ( Tooltip_Debug "PixelSearch_Blue2=[" PixelSearch_Blue2 "]" "`n" ) Tooltip, % ( ( DebugMode == 1 ) ? ( Tooltip_Debug ) : ( Tooltip_Header ) ), 1, 1 If ( PixelSearch_Blue1 || PixelSearch_Blue2 ) { Break } } Sleep 250 ControlClick, x%xpos% y%ypos%, %WinTitle% Sleep 100 Tooltip_Header := "Youtube - Click 'Next' > 'Next' > 'Save'" Tooltip, % ( Tooltip_Header ), 1, 112 xpos := 1274 ypos := 1313 xpos_rightedge := xpos + 20 Loop 3 { Loop { Sleep 100 Color_xpos_ypos := PixelGetColor(xpos, ypos) PixelSearch_Blue1 := PixelSearch( Px, Py, xpos, ypos, xpos_rightedge, ypos, 0x065FD4, 50 ) PixelSearch_Blue2 := PixelSearch( Px, Py, xpos, ypos, xpos_rightedge, ypos, 0x196CD7, 50 ) Tooltip_Debug := ( Tooltip_Header "`n" ) Tooltip_Debug := ( Tooltip_Debug "Color_xpos_ypos=[" Color_xpos_ypos "]" "`n" ) Tooltip_Debug := ( Tooltip_Debug "PixelSearch_Blue1=[" PixelSearch_Blue1 "]" "`n" ) Tooltip_Debug := ( Tooltip_Debug "PixelSearch_Blue2=[" PixelSearch_Blue2 "]" "`n" ) Tooltip, % ( ( DebugMode == 1 ) ? ( Tooltip_Debug ) : ( Tooltip_Header ) ), 1, 1 If ( PixelSearch_Blue1 || PixelSearch_Blue2 ) { Break } } ControlClick, x%xpos% y%ypos%, %WinTitle% Sleep 100 } Sleep 100 Tooltip_Header := "Youtube - Click 'Close'" Tooltip, % ( Tooltip_Header ), 1, 112 xpos := 1056 ypos := 955 xpos_rightedge := xpos + 20 Loop { Sleep 100 Color_xpos_ypos := PixelGetColor(xpos, ypos) PixelSearch_Blue1 := PixelSearch( Px, Py, xpos, ypos, xpos_rightedge, ypos, 0x065FD4, 50 ) PixelSearch_Blue2 := PixelSearch( Px, Py, xpos, ypos, xpos_rightedge, ypos, 0x196CD7, 50 ) Tooltip_Debug := ( Tooltip_Header "`n" ) Tooltip_Debug := ( Tooltip_Debug "Color_xpos_ypos=[" Color_xpos_ypos "]" "`n" ) Tooltip_Debug := ( Tooltip_Debug "PixelSearch_Blue1=[" PixelSearch_Blue1 "]" "`n" ) Tooltip_Debug := ( Tooltip_Debug "PixelSearch_Blue2=[" PixelSearch_Blue2 "]" "`n" ) Tooltip, % ( ( DebugMode == 1 ) ? ( Tooltip_Debug ) : ( Tooltip_Header ) ), 1, 112 If ( PixelSearch_Blue1 || PixelSearch_Blue2 ) { Break } } ControlClick, x%xpos% y%ypos%, %WinTitle% Sleep 250 } } ClearTooltip(10000) Return } ; ------------------------------------------------------------ ; ; Laptop Brightness Class ; BS := new BrightnessSetter() ; PgUp::BS.SetBrightness(10) ; PgDn::BS.SetBrightness(-10) ; class BrightnessSetter { ; qwerty12 - 27/05/17 ; https://github.com/qwerty12/AutoHotkeyScripts/tree/master/LaptopBrightnessSetter static _WM_POWERBROADCAST := 0x218, _osdHwnd := 0, hPowrprofMod := DllCall("LoadLibrary", "Str", "powrprof.dll", "Ptr") __New() { if (BrightnessSetter.IsOnAc(AC)) this._AC := AC if ((this.pwrAcNotifyHandle := DllCall("RegisterPowerSettingNotification", "Ptr", A_ScriptHwnd, "Ptr", BrightnessSetter._GUID_ACDC_POWER_SOURCE(), "UInt", DEVICE_NOTIFY_WINDOW_HANDLE := 0x00000000, "Ptr"))) ; Sadly the callback passed to *PowerSettingRegister*Notification runs on a new threadl OnMessage(this._WM_POWERBROADCAST, ((this.pwrBroadcastFunc := ObjBindMethod(this, "_On_WM_POWERBROADCAST")))) } __Delete() { if (this.pwrAcNotifyHandle) { OnMessage(BrightnessSetter._WM_POWERBROADCAST, this.pwrBroadcastFunc, 0) ,DllCall("UnregisterPowerSettingNotification", "Ptr", this.pwrAcNotifyHandle) ,this.pwrAcNotifyHandle := 0 ,this.pwrBroadcastFunc := "" } } SetBrightness(increment, jump := False, showOSD := True, autoDcOrAc := -1, ptrAnotherScheme := 0) { static PowerGetActiveScheme := DllCall("GetProcAddress", "Ptr", BrightnessSetter.hPowrprofMod, "AStr", "PowerGetActiveScheme", "Ptr") ,PowerSetActiveScheme := DllCall("GetProcAddress", "Ptr", BrightnessSetter.hPowrprofMod, "AStr", "PowerSetActiveScheme", "Ptr") ,PowerWriteACValueIndex := DllCall("GetProcAddress", "Ptr", BrightnessSetter.hPowrprofMod, "AStr", "PowerWriteACValueIndex", "Ptr") ,PowerWriteDCValueIndex := DllCall("GetProcAddress", "Ptr", BrightnessSetter.hPowrprofMod, "AStr", "PowerWriteDCValueIndex", "Ptr") ,PowerApplySettingChanges := DllCall("GetProcAddress", "Ptr", BrightnessSetter.hPowrprofMod, "AStr", "PowerApplySettingChanges", "Ptr") if (increment == 0 && !jump) { if (showOSD) BrightnessSetter._ShowBrightnessOSD() return } if (!ptrAnotherScheme ? DllCall(PowerGetActiveScheme, "Ptr", 0, "Ptr*", currSchemeGuid, "UInt") == 0 : DllCall("powrprof\PowerDuplicateScheme", "Ptr", 0, "Ptr", ptrAnotherScheme, "Ptr*", currSchemeGuid, "UInt") == 0) { if (autoDcOrAc == -1) { if (this != BrightnessSetter) { AC := this._AC } else { if (!BrightnessSetter.IsOnAc(AC)) { DllCall("LocalFree", "Ptr", currSchemeGuid, "Ptr") return } } } else { AC := !!autoDcOrAc } currBrightness := 0 if (jump || BrightnessSetter._GetCurrentBrightness(currSchemeGuid, AC, currBrightness)) { maxBrightness := BrightnessSetter.GetMaxBrightness() ,minBrightness := BrightnessSetter.GetMinBrightness() if (jump || !((currBrightness == maxBrightness && increment > 0) || (currBrightness == minBrightness && increment < minBrightness))) { if (currBrightness + increment > maxBrightness) increment := maxBrightness else if (currBrightness + increment < minBrightness) increment := minBrightness else increment += currBrightness if (DllCall(AC ? PowerWriteACValueIndex : PowerWriteDCValueIndex, "Ptr", 0, "Ptr", currSchemeGuid, "Ptr", BrightnessSetter._GUID_VIDEO_SUBGROUP(), "Ptr", BrightnessSetter._GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS(), "UInt", increment, "UInt") == 0) { ; PowerApplySettingChanges is undocumented and exists only in Windows 8+. Since both the Power control panel and the brightness slider use this, we'll do the same, but fallback to PowerSetActiveScheme if on Windows 7 or something if (!PowerApplySettingChanges || DllCall(PowerApplySettingChanges, "Ptr", BrightnessSetter._GUID_VIDEO_SUBGROUP(), "Ptr", BrightnessSetter._GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS(), "UInt") != 0) DllCall(PowerSetActiveScheme, "Ptr", 0, "Ptr", currSchemeGuid, "UInt") } } if (showOSD) BrightnessSetter._ShowBrightnessOSD() } DllCall("LocalFree", "Ptr", currSchemeGuid, "Ptr") } } IsOnAc(ByRef acStatus) { static SystemPowerStatus if (!VarSetCapacity(SystemPowerStatus)) VarSetCapacity(SystemPowerStatus, 12) if (DllCall("GetSystemPowerStatus", "Ptr", &SystemPowerStatus)) { acStatus := NumGet(SystemPowerStatus, 0, "UChar") == 1 return True } return False } GetDefaultBrightnessIncrement() { static ret := 10 DllCall("powrprof\PowerReadValueIncrement", "Ptr", BrightnessSetter._GUID_VIDEO_SUBGROUP(), "Ptr", BrightnessSetter._GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS(), "UInt*", ret, "UInt") return ret } GetMinBrightness() { static ret := -1 if (ret == -1) if (DllCall("powrprof\PowerReadValueMin", "Ptr", BrightnessSetter._GUID_VIDEO_SUBGROUP(), "Ptr", BrightnessSetter._GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS(), "UInt*", ret, "UInt")) ret := 0 return ret } GetMaxBrightness() { static ret := -1 if (ret == -1) if (DllCall("powrprof\PowerReadValueMax", "Ptr", BrightnessSetter._GUID_VIDEO_SUBGROUP(), "Ptr", BrightnessSetter._GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS(), "UInt*", ret, "UInt")) ret := 100 return ret } _GetCurrentBrightness(schemeGuid, AC, ByRef currBrightness) { static PowerReadACValueIndex := DllCall("GetProcAddress", "Ptr", BrightnessSetter.hPowrprofMod, "AStr", "PowerReadACValueIndex", "Ptr") ,PowerReadDCValueIndex := DllCall("GetProcAddress", "Ptr", BrightnessSetter.hPowrprofMod, "AStr", "PowerReadDCValueIndex", "Ptr") return DllCall(AC ? PowerReadACValueIndex : PowerReadDCValueIndex, "Ptr", 0, "Ptr", schemeGuid, "Ptr", BrightnessSetter._GUID_VIDEO_SUBGROUP(), "Ptr", BrightnessSetter._GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS(), "UInt*", currBrightness, "UInt") == 0 } _ShowBrightnessOSD() { static PostMessagePtr := DllCall("GetProcAddress", "Ptr", DllCall("GetModuleHandle", "Str", "user32.dll", "Ptr"), "AStr", A_IsUnicode ? "PostMessageW" : "PostMessageA", "Ptr") ,WM_SHELLHOOK := DllCall("RegisterWindowMessage", "Str", "SHELLHOOK", "UInt") if ((A_OSVersion=="WIN_VISTA")||(A_OSVersion=="WIN_7")) return BrightnessSetter._RealiseOSDWindowIfNeeded() ; Thanks to YashMaster @ https://github.com/YashMaster/Tweaky/blob/master/Tweaky/BrightnessHandler.h for realising this could be done: if (BrightnessSetter._osdHwnd) DllCall(PostMessagePtr, "Ptr", BrightnessSetter._osdHwnd, "UInt", WM_SHELLHOOK, "Ptr", 0x37, "Ptr", 0) } _RealiseOSDWindowIfNeeded() { static IsWindow := DllCall("GetProcAddress", "Ptr", DllCall("GetModuleHandle", "Str", "user32.dll", "Ptr"), "AStr", "IsWindow", "Ptr") if (!DllCall(IsWindow, "Ptr", BrightnessSetter._osdHwnd) && !BrightnessSetter._FindAndSetOSDWindow()) { BrightnessSetter._osdHwnd := 0 try if ((shellProvider := ComObjCreate("{C2F03A33-21F5-47FA-B4BB-156362A2F239}", "{00000000-0000-0000-C000-000000000046}"))) { try if ((flyoutDisp := ComObjQuery(shellProvider, "{41f9d2fb-7834-4ab6-8b1b-73e74064b465}", "{41f9d2fb-7834-4ab6-8b1b-73e74064b465}"))) { DllCall(NumGet(NumGet(flyoutDisp+0)+3*A_PtrSize), "Ptr", flyoutDisp, "Int", 0, "UInt", 0) ,ObjRelease(flyoutDisp) } ObjRelease(shellProvider) if (BrightnessSetter._FindAndSetOSDWindow()) return } ; who knows if the SID & IID above will work for future versions of Windows 10 (or Windows 8). Fall back to this if needs must Loop 2 { SendEvent {Volume_Mute 2} if (BrightnessSetter._FindAndSetOSDWindow()) return Sleep 100 Random, RandomSleep, 1000, 1500 Sleep %RandomSleep% } } } _FindAndSetOSDWindow() { static FindWindow := DllCall("GetProcAddress", "Ptr", DllCall("GetModuleHandle", "Str", "user32.dll", "Ptr"), "AStr", A_IsUnicode ? "FindWindowW" : "FindWindowA", "Ptr") return !!((BrightnessSetter._osdHwnd := DllCall(FindWindow, "Str", "NativeHWNDHost", "Str", "", "Ptr"))) } _On_WM_POWERBROADCAST(wParam, lParam) { ;OutputDebug % &this if (wParam == 0x8013 && lParam && NumGet(lParam+0, 0, "UInt") == NumGet(BrightnessSetter._GUID_ACDC_POWER_SOURCE()+0, 0, "UInt")) { ; PBT_POWERSETTINGCHANGE and a lazy comparison this._AC := NumGet(lParam+0, 20, "UChar") == 0 return True } } _GUID_VIDEO_SUBGROUP() { static GUID_VIDEO_SUBGROUP__ if (!VarSetCapacity(GUID_VIDEO_SUBGROUP__)) { VarSetCapacity(GUID_VIDEO_SUBGROUP__, 16) ,NumPut(0x7516B95F, GUID_VIDEO_SUBGROUP__, 0, "UInt"), NumPut(0x4464F776, GUID_VIDEO_SUBGROUP__, 4, "UInt") ,NumPut(0x1606538C, GUID_VIDEO_SUBGROUP__, 8, "UInt"), NumPut(0x99CC407F, GUID_VIDEO_SUBGROUP__, 12, "UInt") } return &GUID_VIDEO_SUBGROUP__ } _GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS() { static GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS__ if (!VarSetCapacity(GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS__)) { VarSetCapacity(GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS__, 16) ,NumPut(0xADED5E82, GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS__, 0, "UInt"), NumPut(0x4619B909, GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS__, 4, "UInt") ,NumPut(0xD7F54999, GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS__, 8, "UInt"), NumPut(0xCB0BAC1D, GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS__, 12, "UInt") } return &GUID_DEVICE_POWER_POLICY_VIDEO_BRIGHTNESS__ } _GUID_ACDC_POWER_SOURCE() { static GUID_ACDC_POWER_SOURCE_ if (!VarSetCapacity(GUID_ACDC_POWER_SOURCE_)) { VarSetCapacity(GUID_ACDC_POWER_SOURCE_, 16) ,NumPut(0x5D3E9A59, GUID_ACDC_POWER_SOURCE_, 0, "UInt"), NumPut(0x4B00E9D5, GUID_ACDC_POWER_SOURCE_, 4, "UInt") ,NumPut(0x34FFBDA6, GUID_ACDC_POWER_SOURCE_, 8, "UInt"), NumPut(0x486551FF, GUID_ACDC_POWER_SOURCE_, 12, "UInt") } return &GUID_ACDC_POWER_SOURCE_ } } BrightnessSetter_new() { return new BrightnessSetter() } ; ------------------------------------------------------------ ; ; Under Construction: Duplicate currently-active Window ; | ; |--> Planned Workflow & Features (Pseudocode): ; | ; |--> Get Active Window's EXE-Filepath ; | ; |--> Get Active Window's Runtime-Parameters ; | |--> Ask user if they want to run with [ same runtime parameters as active window ] or [ input their own runtime parameters (string input from user because of open-ended-ness) ] ; | |--> Ask user if they want to [ run WITH elevated privileges ] or [ run WITHOUT elevated privileges ] ; | ; |--> Run [ EXE-Filepath ] with [ Runtime-Parameters ] determined by user (above) ; ; ; ;;; ;;; ;;;;; ADD NEW SCRIPTS HERE ;;;;; ;;; ;;; ; ; ; ; ;;; ;;; ;;;;; ADD NEW SCRIPTS HERE ;;;;; ;;; ;;; ; ; ; ; ;;; ;;; ;;;;; ADD NEW SCRIPTS HERE ;;;;; ;;; ;;; ; ; ; ------------------------------------------------------------ ; Documentation ; ------------------------------------------------------------ ; ; SetTitleMatchMode, 1 ; A window's title must start with the specified WinTitle to be a match ; SetTitleMatchMode, 2 ; A window's title can contain WinTitle anywhere inside it to be a match ; SetTitleMatchMode, 3 ; A window's title must exactly match WinTitle to be a match ; ; ; ------------------------------------------------------------ ; ; *** To obtain the unique code(s) thrown by the keyboard per-keypress: ; ; // Create a separate AutoHotkey (.ahk) Script and paste these 3 lines into ; // it. Make sure to save it with a .ahk file extension: ; ; ----- BEGIN KEY-CODE LO ----- ; #InstallKeybdHook ; #Persistent ; KeyHistory ; ----- END OF FILE ----- ; ; // NOTE: After you've saved it, run it, and a command prompt (w/ white background) will ; // display the codes for any key pressed while it is running. ; ; // SC: Refer to the "SC" column to acquire the "scan code" of any keys pressed (string, length 3) ; // VK: Refer to the "VK" column to acquire the "virtual key code" of any keys pressed (string, length 2) ; // Key: Refer to the "Key" column to acquire the "Hotstring" of any keys pressed (string, length varies) ; ; // NOTE: If the above method fails, refer to: https://www.autohotkey.com/docs/commands/GetKey.htm ; ; ------------------------------------------------------------ ; ; *** TO DETERMINE THE COMMAND BEING SENT: ; SC029:: ; SplashTextOn, 250, 40, Debugging, Command Sent ; Sleep 500 ; Random, RandomSleep, 1000, 1500 ; Sleep %RandomSleep% ; SplashTextOff ; -- Remainder of your script ; ; ------------------------------------------------------------ ; ; MouseClick,[Button],[X_Coord],[Y_Coord],[ClickCount],[Speed],[U|D],[Relative] ; ; PARAMS: ; [Button] = { Left, Right, Middle, X1, X2, WheelUp (or WU), WheelDown (or WD), WheelLeft (or WL), WheelRight (or WR) --- DEFAULTS TO LEFT IF OMITTED } ; [X_Coord] = { Screen Horizontal-Position to fire the click --- DEFAULTS TO CURRENT CURSOR X-COORDINATE } ; [Y_Coord] = { Screen Vertical-Position to fire the click --- DEFAULTS TO CURRENT CURSOR Y-COORDINATE } ; [ClickCount] = { Click this many times --- DEFAULTS TO 1 CLICK, IF OMITTED } ; [Speed] = { Movement speed of mouse across the screen - 0 is Instant --- DEFAULTS TO DEFAULT MOUSE MOVE SPEED SET BY [SetDefaultMouseSpeed, Speed], OTHERWISE DEFAULTS TO 2 } ; [U|D] = { Only do a Click-Down (D) or Click-Up (U) click-event --- DEFAULTS A *DOWN* FOLLOWED BY AN *UP* EVENT, IF OMITTED} ; [Relative] = { If set to (R), the X & Y Coordinates will be treated as an offset to mouse's current position --- DEFAULTS TO NON-RELATIVE MOVEMENT, IF OMITTED } ; ; ------------------------------------------------------------ ; ; MouseClickDrag, WhichButton, X1, Y1, X2, Y2 [, Speed, R] ; ; ------------------------------------------------------------ ; ; MouseMove, X, Y [, Speed, R] ; ; ------------------------------------------------------------ ; ; EXAMPLE_ControlClick() { ; ;;; ; ;;; ControlClick [, Control-or-Pos, WinTitle, WinText, WhichButton, ClickCount, Options, ExcludeTitle, ExcludeText] ; ;;; ; CoordMode, Mouse, Screen ; SetDefaultMouseSpeed, 0 ; SetControlDelay, -1 ; ; WinGetTitle, WinTitle, A ; WinTitle := "NoxPlayer" ; xpos := (A_ScreenWidth - 20) ; ypos := 315 ; ControlClick, x%xpos% y%ypos%, %WinTitle% ; } ; ; ------------------------------------------------------------ ; ; MsgBox has tons of options for confirmations on popups ( Manual @ https://www.autohotkey.com/docs/commands/MsgBox.htm ) ; ...:: ; WinGetActiveStats, WinTitle, Width, Height, X, Y ; WinGetText, WinText, A ; MsgBox, 4, , WinTitle `n%WinTitle% `n`nWindow Size: `n Width (%Width%) Height (%Height%) `n`nWindow Coordinates: `n X (%X%) Y (%Y%) `n`nSkip WinText?, 10 ; 10-second timeout. ; If (A_MsgBoxResult = "Yes") ; Return ; If (A_MsgBoxResult = "No") ; MsgBox, WinText `n%WinText% ; Return ; If (A_MsgBoxResult = "Timeout") ; Return ; Return ; ; ------------------------------------------------------------ ; ; ; Menu, tray, add ; Creates a separator line. ; Menu, tray, add, "Lineage-2", MenuHandler ; Creates a new menu item. ; return ; ; MenuHandler: ; MsgBox You selected %A_ThisMenuItem% from menu %A_ThisMenu%. ; MsgBox A_TitleMatchMode[%A_TitleMatchMode%], A_TitleMatchModeSpeed=[%A_TitleMatchModeSpeed%] ; return ; ; Menu, FileMenu, Add, Script Icon, MenuHandler_FileMenu ; Menu, FileMenu, Add, Suspend Icon, MenuHandler_FileMenu ; Menu, FileMenu, Add, Pause Icon, MenuHandler_FileMenu ; Menu, FileMenu, Icon, Script Icon, %A_AhkPath%, 2 ;Use the 2nd icon group from the file ; Menu, FileMenu, Icon, Suspend Icon, %A_AhkPath%, -206 ;Use icon with resource identifier 206 ; Menu, FileMenu, Icon, Pause Icon, %A_AhkPath%, -207 ;Use icon with resource identifier 207 ; Menu, MyMenuBar, Add, &File, :FileMenu ; Gui, Menu, MyMenuBar ; Gui, Add, Button, gExit, Exit This Example ; Gui, Show ; MenuHandler_FileMenu: ; Return ; ; Exit: ; ExitApp ; ; Example: Using in-line if conditional(s) ; ; y := ( ( y = 8 ) ? ( 2008 ) : ( ( y = 9 ) ? ( 2009 ) : ( ( y = 0 ) ? ( 2010 ) : ( 2011 ) ) ) ) ; ; ------------------------------------------------------------ ; ; Example: Compare two Strings' Displayed Character-Widths (Strlen doesn't have a whole lot to do with actual/displayed character-widths) ; ; CompareCharacterWidths() { ; Newline=`n ; Echo1= String = [ chr(0x0061) ] Strlen = [ StrLen( chr(0x0061) ) ] ; Echo2= String = [ chr(0x030a) ] Strlen = [ StrLen( chr(0x030a) ) ] ; Echo_Tooltip= ; Echo_Tooltip := Echo_Tooltip Newline " String=|" chr(0x0061) "| StrLen=|" StrLen( chr(0x0061) ) "|" ; Echo_Tooltip := Echo_Tooltip Newline A_Space ; Echo_Tooltip := Echo_Tooltip Newline " String=|" chr(0x030a) "| StrLen=|" StrLen( chr(0x030a) ) "|" ; Echo_Tooltip := Echo_Tooltip Newline A_Space ; MsgBox, %Echo_Tooltip% ; Return ; } ; ------------------------------------------------------------ ; ; ;;; Example: Custom Popups ; ; CustomPopupButtons_Demo() { ; ; SetTimer, CustomMsgboxButtons_UNIQUE_NAME_HERE, 50 ; ; |--> Ensure that this callback script kills this SetTimer, otherwise it will keep running indefinitely ; ; MsgBox, 3, Popup_MsgBox_WindowTitle, Popup MsgBox Question? or Statement! ; ; If (A_MsgBoxResult = "Yes") { ; TrayTip, AHK, % ( "Leftmost Button Selected" ) ; Toast Notification ; } ; If (A_MsgBoxResult = "No") { ; TrayTip, AHK, % ( "Center Button Selected" ) ; Toast Notification ; } ; If (A_MsgBoxResult = "Cancel") { ; TrayTip, AHK, % ( "Rightmost Button Selected" ) ; Toast Notification ; } ; ; Return ; ; } ; ; CustomMsgboxButtons_UNIQUE_NAME_HERE() { ; If (WinExist(Popup_MsgBox_WindowTitle)) { ; Return ; Continue waiting for the "Clipboard or ClipboardAll" window to appear ; } ; SetTimer, CustomMsgboxButtons_UNIQUE_NAME_HERE, Off ; WinActivate ; ControlSetText, Button1, &LEFT_BUTTON ; ControlSetText, Button2, &CENTER_BUTTON ; ControlSetText, Button3, &RIGHT_BUTTON ; Return ; } ; ; ; ------------------------------------------------------------ ; ; Alphabetical Command and Function Index: https://www.autohotkey.com/docs/commands/ ; |--> Clipboard: https://www.autohotkey.com/docs/misc/Clipboard.htm ; |--> ControlGetText: https://www.autohotkey.com/docs/commands/ControlGetText.htm ; |--> For Each: https://www.autohotkey.com/docs/commands/For.htm ; |--> GetKeyState: https://www.autohotkey.com/docs/commands/GetKeyState.htm ; |--> Hotkey: https://www.autohotkey.com/docs/commands/Hotkey.htm#IfWin ; |--> KeyWait: https://www.autohotkey.com/docs/commands/KeyWait.htm ; |--> Loop Parse: https://www.autohotkey.com/docs/commands/LoopParse.htm ; |--> Menu: https://www.autohotkey.com/docs/commands/Menu.htm ; |--> RegExReplace: https://www.autohotkey.com/docs/commands/RegExReplace.htm ; |--> Run/RunWait: https://www.autohotkey.com/docs/commands/Run.htm ; |--> SetTimer: https://www.autohotkey.com/docs/commands/SetTimer.htm ; |--> SysGet: https://www.autohotkey.com/docs/commands/SysGet.htm ; |--> SplitPath: https://www.autohotkey.com/docs/commands/SplitPath.htm ; ; ------------------------------------------------------------ ; ; Variables and Expressions: https://www.autohotkey.com/docs/Variables.htm#BuiltIn ; | ; |--> Operators in Expressions - If (...) statements, including mathematical operators: https://www.autohotkey.com/docs/Variables.htm#Operators ; | ; |--> Arrays/Objects - Simple Arrays, e.g. "Indexed Arrays": https://www.autohotkey.com/docs/Objects.htm#Usage_Simple_Arrays ; | ; |--> Arrays/Objects - Associative Arrays, e.g. "Associative Arrays": https://www.autohotkey.com/docs/Objects.htm#Usage_Associative_Arrays ; | ; |--> Arrays/Objects - Pseudo-Arrays, e.g. "Variable Variables" (AVOID these to maintain syntax legibility & understandability): https://www.autohotkey.com/docs/misc/Arrays.htm#pseudo ; ; ------------------------------------------------------------ ; ; List of Keys: https://www.autohotkey.com/docs/KeyList.htm ; | ; |--> Modifiers Keys: https://www.autohotkey.com/docs/KeyList.htm#modifier ; | ; |--> Multimedia Keys: https://www.autohotkey.com/docs/KeyList.htm#multimedia ; ; ------------------------------------------------------------ ; ; Remapping Keys (Keyboard, Mouse and Joystick): https://www.autohotkey.com/docs/misc/Remap.htm ; ; ------------------------------------------------------------ ; ; Hotkeys (Mouse, Joystick and Keyboard Shortcuts): https://www.autohotkey.com/docs/Hotkeys.htm#Symbols ; | ; |--> Hotkey Modifier Symbols: https://www.autohotkey.com/docs/Hotkeys.htm#Symbols ; ; # Win ; ; ! Alt ; ; + Shift ; ; ^ Ctrl ; ; NOTE: Most full-sized querty keyboards have two of each modifier key, one to the left-side of the spacebar, one to the right ; ; < Use the LEFT modifier key, e.g. <# (LWin), Use the RIGHT modifier key, e.g. ># (RWin), >! (RAlt), >+ (RShift), >^ (RCtrl) ; ; AppsKey (Application or Menu key, keycap symbol looks like a document w/ 3 lines) ; ; ------------------------------------------------------------ ; ; Citation(s) ; ; answers.microsoft.com | "Shortcut to sound control panel?" | https://answers.microsoft.com/en-us/windows/forum/windows_10-start/shortcut-to-sound-control-panel/32d5a6e7-fa92-4ca7-9033-cd38ba525542 ; ; docs.microsoft.com | "wscript | Microsoft Docs" | https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/wscript ; ; docs.microsoft.com | "WM_SYSCOMMAND message" | https://docs.microsoft.com/en-us/windows/win32/menurc/wm-syscommand ; ; gist.github.com | "Media keys shortcuts for AutoHotkey · GitHub" | https://gist.github.com/mistic100/d3c0c1eb63fb7e4ee545 ; ; github.com | "AutoHotkeyScripts/LaptopBrightnessSetter at master · qwerty12/AutoHotkeyScripts · GitHub" | https://github.com/qwerty12/AutoHotkeyScripts/tree/master/LaptopBrightnessSetter ; ; stackoverflow.com | "How can I set AutoHotKey's code to run only in chrome?" | https://stackoverflow.com/a/50180863 ; ; stackoverflow.com | "powershell - Setting screen resolution on Windows 10 - Stack Overflow" | https://stackoverflow.com/a/49375988 ; ; www.autohotkey.com | "Advanced Hotkey Features | AutoHotkey" | https://www.autohotkey.com/docs/HotkeyFeatures.htm#pass-through ; ; www.autohotkey.com | "CLSID List (Windows Class Identifiers)" | https://www.autohotkey.com/docs/misc/CLSID-List.htm <-- Example) ::{7007acc7-3202-11d1-aad2-00805fc1270e} ; ; www.autohotkey.com | "ControlGet List - Ask for Help - AutoHotkey Community" | https://autohotkey.com/board/topic/7649-controlget-list/ ; ; www.autohotkey.com | "Detect Current Windows Domain - Ask for Help - AutoHotkey Community" | https://autohotkey.com/board/topic/77940-detect-current-windows-domain/?p=495386 ; ; www.autohotkey.com | "determine if scaling is not 100% for monitor of a window, change PerMonitorSettings in registry, reflect change, verify - AutoHotkey Community" | https://www.autohotkey.com/boards/viewtopic.php?p=160615#p160615 ; ; www.autohotkey.com | "escape double quote - AutoHotkey Community" | https://www.autohotkey.com/boards/viewtopic.php?t=14082 ; ; www.autohotkey.com | "Get Current Micro/Nano seconds" | https://www.autohotkey.com/boards/viewtopic.php?p=126168#p126168 ; ; www.autohotkey.com | "Get Highest and Lowest value - Ask for Help - AutoHotkey Community" | https://autohotkey.com/board/topic/88376-get-highest-and-lowest-value/?p=560579 ; ; www.autohotkey.com | "How to make AHK to type braces (curly brackets) - AutoHotkey Community" | https://www.autohotkey.com/boards/viewtopic.php?p=346714&sid=cf868beb68d8b6fefc7e3e69e7cdaeea#p346714 ; ; www.autohotkey.com | "How to paste multiline text - Ask for Help - AutoHotkey Community" | https://www.autohotkey.com/board/topic/65421-how-to-paste-multiline-text/ ; ; www.autohotkey.com | "How to quickly generate random strings? - AutoHotkey Community" | https://www.autohotkey.com/boards/viewtopic.php?t=76052 ; ; www.autohotkey.com | "How can I send a Windows toast notification? (TrayTip)" | https://www.autohotkey.com/boards/viewtopic.php?p=63507&sid=14b947240a145197c869c413824d8c50#p63507 ; ; www.autohotkey.com | "If Expression check to see if value is in Array" | https://www.autohotkey.com/boards/viewtopic.php?p=52627&sid=4e5a541af8d29ab16154c5a6dd379620#p52627 ; ; www.autohotkey.com | "ListView - G-Label Notifications (Primary)" | https://www.autohotkey.com/docs/commands/ListView.htm#notify ; ; www.autohotkey.com | "Move window to half / quarter of current monitor - Scripts and Functions - AutoHotkey Community" | https://www.autohotkey.com/board/topic/108780-move-window-to-half-quarter-of-current-monitor/?p=648327 ; ; www.autohotkey.com | "Optimize StrLen, Unicode Version" | https://www.autohotkey.com/boards/viewtopic.php?p=106284#p106284 ; ; www.autohotkey.com | "Options and Styles for "Gui, Add, ListView, Options" | https://www.autohotkey.com/docs/commands/ListView.htm#Options ; ; www.autohotkey.com | "PostMessage/SendMessage - #1: Press Win+O to turn off the monitor" | https://www.autohotkey.com/docs/commands/PostMessage.htm#ExMonitorPower ; ; www.autohotkey.com | "PostMessage/SendMessage - #2: Start the user's chosen screen saver" | https://www.autohotkey.com/docs/commands/PostMessage.htm#ExScreenSave ; ; www.autohotkey.com | "Run[Wait] Example #2: The following can be used to run a command and retrieve its output:" | https://www.autohotkey.com/docs/commands/Run.htm#StdOut ; ; www.autohotkey.com | "SendInput %Clipboard% adds double linebreaks for Multiline - Ask for Help - AutoHotkey Community" | https://autohotkey.com/board/topic/88346-sendinput-clipboard-adds-double-linebreaks-for-multiline/ ; ; www.autohotkey.com | "Single line if statements" | https://www.autohotkey.com/board/topic/74001-single-line-if-statements/?p=470078 ; ; www.autohotkey.com | "Trim multiple lines" | https://www.autohotkey.com/boards/viewtopic.php?p=175097#p175097 ; ; www.autohotkey.com | "Windows 10? AutoHotkey Window Title, etc. - AutoHotkey Community" | https://www.autohotkey.com/boards/viewtopic.php?p=164262#p164262 ; ; www.autohotkey.com | "[HELP!] How to WinActivate without specifying window title? - Ask for Help - AutoHotkey Community" | https://www.autohotkey.com/board/topic/102763-help-how-to-winactivate-without-specifying-window-title/ ; ; www.reddit.com | "Brightness script? : AutoHotkey" | https://www.reddit.com/r/AutoHotkey/comments/5u2lvi/brightness_script/ ; ; www.reddit.com | "Possible to do SubStr() on multiple lines at once? : AutoHotkey" | https://www.reddit.com/r/AutoHotkey/comments/9f0qan/possible_to_do_substr_on_multiple_lines_at_once/ ; ; www.tenforums.com | "Resolution mismatch when using "Change the size of text..." - Windows 10 Forums" | https://www.tenforums.com/general-support/69742-resolution-mismatch-when-using-change-size-text.html#post869493 ; ; ------------------------------------------------------------