Lorenzo501

Time Saver (redundant version of God Mode).ahk

Dec 18th, 2024 (edited)
29
0
Never
6
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.     This is a productivity enhancer plus some quality-of-life features that takes care of tedious tasks for you, saving time for what matters. Click on the tray icon to view hotkey info.
  3.     You'll find an embedded INI at the bottom of this script. However, you have to follow these two steps before you can run this script:
  4.     Download and unzip archive in `Lib` folder: https://github.com/thqby/winrt.ahk
  5.     Download raw file into `Lib` folder: https://github.com/Descolada/UIA-v2/blob/main/Lib/UIA.ahk
  6.  
  7.     ********** EIGHT-HOTKEY REMOTE **********
  8.     Multi- and single-function hotkeys.
  9.     TIP: change the `Run` setting to `Maximize` in the properties wnd of the Paint shortcut (b/c the snip feature can open Paint in a small wnd, which will be remembered by the OS).
  10.         And go to `Settings > System > Focus assist` to turn off all `Automatic rules`, so that TrayTip notification banners can also be shown on the desktop wnd for example.
  11.  
  12.     Pause = MEDIA CONTROL
  13.         Quick-press to play/pause, double-press to play next & triple-press to play previous.
  14.     Win+G = GOD MODE
  15.         Quick-press to trigger god mode (a destination runs depending on the active/existing context wnd). Double-press to use active context wnd for selectable destination folder.
  16.         Long-press to use active context wnd for existing folder wnd (necessary for special folders). Triple-press to use active context wnd for typeable non-folder destination.
  17.     Win+R = SMART RUN
  18.         Quick-press to open Run dialog with preferred input & double-press or long-press to configure preferred input.
  19.     Win+C = CALC/CTRL
  20.         Quick-press to open Calculator & double-press or long-press to display control list of active wnd in realtime.
  21.     Win+S = SNIP
  22.         Start snip to clipboard (editable through Paint once you click the TrayTip that disappears after 10 min).
  23.     PrtScn = SCREENSHOT+
  24.         Quick-press to use native fn, double-press to save to desktop as well & long-press to merely save a clipboard image to desktop (does nothing if the clipboard has none).
  25.     XButton* = MOUSE MENU
  26.         Pressed down to show two-option menu & release to select.
  27.     MButton = CONCEAL CARET
  28.         Toggle caret in Notepad, VS Code or Visual Studio.
  29.  
  30.     ********** AUTOMATION FEATURES **********
  31.  
  32.     Open a network stream in VLC once you click `Copy Stream URL` in uTorrent.
  33.     Assist the Chrome extension `Tabs Outliner` by making sure it has finished saving before getting closed.
  34.     Auto-run Outlook minimized, this will allow you to see the unread emails badge for emails that you receive afterwards (so you might still want to check in the app at computer startup).
  35.         And also make the close btn minimize Outlook instead, and make each button work wherever you click on them (Outlook normally doesn't respond to clicks at the first line of pixels).
  36.         TIP: you can swap the badge file for another here: %LocalAppData%\Microsoft\Olk\cache
  37.     Upgrade VLC by opening videos of specific folder(s) with aspect ratio 16:9, changing default settings just once; to enable and fix features, and to prevent repetition and annoyances.
  38.         Showing a close btn in fullscreen when your cursor reaches the top-right corner and making the fullscreen controller immovable, centered at the bottom.
  39.         TIP: you can restore the old settings by replacing this file: %AppData%\vlc\vlcrc, with the backup: %Temp%\vlcrc
  40.     Activate the `Unsaved Changes` dialog when showed and parent wnd first (most importantly the dialog might otherwise not appear when you click the close btn via the preview wnd).
  41.     Unhide taskbar in specific fullscreen window(s) and allow the cursor to move taskbar icons after the LButton has been pressed down for atleast 500 ms (to avoid moving them by mistake).
  42.     Auto-close the annoying WinRAR and Software Ideas Modeler notifications.
  43.     Unfocus the minimized uTorrent window at startup to prevent key presses from affecting it by accident.
  44.         TIP: move script to: %UserProfile%\Downloads\AutoHotkey, after that go to `Task Scheduler > Action > Import Task...` and then use the XML file (the task makes this feature faster).
  45.     Scroll namespace to top when nearby on VS edit control show event.
  46.  
  47.     ********** WINDOWS' BUILT-IN HOTKEYS **********
  48.     Some native hotkeys that you should know about.
  49.  
  50.     Win+D = Show desktop.
  51.     Win+; = Emoji menu (e.g. you could insert a checkmark into a txt file).
  52.     MButton = Cursor on URL opens website in new tab, cursor on app in taskbar opens new instance & cursor on scrollable area of website activates auto-scroll.
  53.     Alt+F4 = When on desktop it'll show the shutdown menu.
  54.     Ctrl+F = Open find wnd (any text that you select beforehand gets inserted into the Find wnd automatically).
  55.     F3 = Quickly find and select text that was previously entered in the find wnd but without having to open the Find wnd again.
  56.     Win+Alt+B = Toggle HDR (this feature has been made reliable with a custom hotkey).
  57.  */
  58. #Requires AutoHotkey 2.1-alpha.9 ; For _menu.Show(,, 0), struct, fn definition expression and `property ??`
  59. #SingleInstance Off
  60. A_DetectHiddenWindows := true
  61.  
  62. ; To make hotkeys work when an admin window is active
  63. if (!InStr(A_AhkPath, "_UIA.exe"))
  64. {
  65.     if (!WinExist(A_ScriptFullPath " ahk_exe AutoHotkey64_UIA.exe"))
  66.         Run("*UIAccess " A_ScriptFullPath)
  67.  
  68.     ExitApp()
  69. }
  70. else if (WinGetList(A_ScriptFullPath " ahk_exe AutoHotkey64_UIA.exe").Length > 1)
  71.     ExitApp()
  72.  
  73. A_DetectHiddenWindows := false
  74. #Include <winrt.ahk-main\windows>
  75. #Include <UIA>
  76. Initialize()
  77.  
  78. ; PowerShell HDR toggle pipe writer (replaces the Windows' built-in HDR toggle hotkey of Game Bar on demand, to make it reliable)
  79. #!b::
  80. {
  81.     if (!RegRead("HKEY_CURRENT_USER\System\GameConfigStore", "GameDVR_Enabled")) ; Detects disabled Game Bar because it shouldn't toggle it with both Game Bar and WindowsDisplayManager
  82.         Run("PowerShell.exe -Command `"" "
  83.         (
  84.             $pipeClient = New-Object System.IO.Pipes.NamedPipeClientStream('.', '\\.\pipe\HdrTogglePipe', [System.IO.Pipes.PipeDirection]::Out)
  85.             $pipeWriter = New-Object System.IO.StreamWriter($pipeClient)
  86.             $pipeClient.Connect()
  87.             $pipeWriter.WriteLine($true)
  88.             $pipeWriter.Flush()
  89.         )" "`"",, "Hide")
  90.  
  91.     KeyWait("LWin") ; Prevents the Win+Alt+B hotkey from triggering again while it's still pressed down
  92. }
  93.  
  94. *Pause::HandleHotkeyActivation(() => Send("{Media_Play_Pause}"), () => Send("{Media_Next}"), () => Send("{Media_Prev}"))
  95.  
  96. ; This hotkey variant uses I1 so that it won't get triggered by I1 WinExist hotkey variants (AHK does not let WinActive hotkey variants get priority by default, so they take care of that)
  97. #InputLevel 1
  98. #g::HandleGodModeHotkeyActivation(() => ShellNavigate("shell:::{ED7BA470-8E54-465E-825C-99712043E01C}"))
  99.  
  100. #InputLevel 0 ; Resets back to default
  101.  
  102. #r::
  103. {
  104.     pressStartTime := A_TickCount
  105.  
  106.     loop
  107.     {
  108.         Sleep(10)
  109.  
  110.         ; Win+R Quick-Press & Double-Press. Opens the run dialog or the configuration dialog for preferred input
  111.         if (!GetKeyState("#", "P") && !GetKeyState("r", "P"))
  112.         {
  113.             HandleHotkeyActivation(StartSmartRun, ConfigurePreferredSmartRunInput)
  114.  
  115.             return
  116.         }
  117.  
  118.         ; Win+R Long-Press. Opens the configuration dialog for preferred input
  119.         if (A_TickCount - pressStartTime > 750)
  120.         {
  121.             ConfigurePreferredSmartRunInput()
  122.             KeyWait("LWin") ; Prevents the Win+R hotkey from triggering again while it's still pressed down
  123.  
  124.             return
  125.         }
  126.     }
  127.  
  128.     StartSmartRun()
  129.     {
  130.         Run("shell:::{2559a1f3-21d7-11d4-bdaf-00c04f60b9f0}")
  131.         WinWaitActive("Run ahk_class #32770")
  132.  
  133.         if (preferredSmartRunInputSection := IniRead(iniPath, "PreferredSmartRunInput"))
  134.             ControlSetText(preferredSmartRunInputSection, "Edit1"), Send("+{End}")
  135.     }
  136.  
  137.     ConfigurePreferredSmartRunInput()
  138.     {
  139.         preferredInput := InputBox("Enter the preferred input to show by default in the Run dialog. "
  140.             "Use %LocalAppData%โ€”it's the one most people tend to use.`n`n"
  141.             "Pro Tip: QuickAssist for remote assistance (built into Windows).", "Preferred Input - Smart Run", "w397 h174", "%LocalAppData%")
  142.  
  143.         if (preferredInput.Result = "OK")
  144.         {
  145.             IniDelete(iniPath, "PreferredSmartRunInput")
  146.             IniWriteExistingContextWindows(preferredInput.Value, "PreferredSmartRunInput") ; Writes it below the godmode sections
  147.         }
  148.     }
  149. }
  150.  
  151. #c::
  152. {
  153.     pressStartTime := A_TickCount
  154.  
  155.     loop
  156.     {
  157.         Sleep(10)
  158.  
  159.         ; Win+C Quick-Press & Double-Press. Opens calculator or toggles the realtime control list
  160.         if (!GetKeyState("#", "P") && !GetKeyState("c", "P"))
  161.         {
  162.             HandleHotkeyActivation(() => Run("Calc"), ToggleRealtimeControlList)
  163.  
  164.             return
  165.         }
  166.  
  167.         ; Win+C Long-Press. This toggles the realtime control list
  168.         if (A_TickCount - pressStartTime > 750)
  169.         {
  170.             ToggleRealtimeControlList()
  171.             KeyWait("LWin") ; Prevents the Win+C hotkey from triggering again while it's still pressed down
  172.  
  173.             return
  174.         }
  175.     }
  176.  
  177.     ToggleRealtimeControlList()
  178.     {
  179.         static shouldShowRealtimeControlList := false
  180.         SetTimer(WatchActiveWindow, (shouldShowRealtimeControlList := !shouldShowRealtimeControlList) ? 200 : 0)
  181.  
  182.         if (!shouldShowRealtimeControlList)
  183.             ToolTip()
  184.  
  185.         WatchActiveWindow()
  186.         {
  187.             if (isToolTipPrtScnShown)
  188.                 return
  189.  
  190.             try
  191.             {
  192.                 focusedHwnd := ControlGetFocus("A")
  193.                 focusedClassNN := ControlGetClassNN(focusedHwnd)
  194.                 controlList := "๐—–๐—ผ๐—ป๐˜๐—ฟ๐—ผ๐—น ๐—Ÿ๐—ถ๐˜€๐˜ ๐—ข๐—ณ ๐—”๐—ฐ๐˜๐—ถ๐˜ƒ๐—ฒ ๐—ช๐—ถ๐—ป๐—ฑ๐—ผ๐˜„: " WinGetProcessName("A")
  195.                     . "`n๐—™๐—ผ๐—ฐ๐˜‚๐˜€๐—ฒ๐—ฑ ๐—–๐—ผ๐—ป๐˜๐—ฟ๐—ผ๐—น: {๐—ต๐—ช๐—ป๐—ฑ: " focusedHwnd ", ๐—–๐—น๐—ฎ๐˜€๐˜€๐—ก๐—ก: `"" focusedClassNN "`"}"
  196.                     . "`nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”`n"
  197.  
  198.                 for (classNN in WinGetControls("A"))
  199.                     controlList .= classNN "`n"
  200.  
  201.                 if (controlList = "")
  202.                     ToolTip("The active window has no controls.", toolTipAxes*)
  203.                 else
  204.                     ToolTip(ControlList, toolTipAxes*)
  205.             }
  206.             catch (TargetError)
  207.                 ToolTip("No visible window is active.", toolTipAxes*)
  208.         }
  209.     }
  210. }
  211.  
  212. #s::
  213. {
  214.     static winEventHook := 0, clipImage
  215.     OnClipboardChange(HandleClipChanged)
  216.     Run("ms-screenclip:")
  217.     WinWait("ahk_exe ScreenClippingHost.exe")
  218.     WinWaitClose("ahk_exe ScreenClippingHost.exe")
  219.     OnClipboardChange(HandleClipChanged, 0)
  220.  
  221.     if (!winEventHook)
  222.         winEventHook := HookEvent(EVENT_OBJECT_NAMECHANGE, HandleNameChangedSnipWinEvent)
  223.  
  224.     ; This (re)sets the timer to 10 minutes
  225.     SetTimer(DismissSnipNotification, -600000)
  226.  
  227.     HandleClipChanged(*) => clipImage := ClipboardAll()
  228.  
  229.     HandleNameChangedSnipWinEvent(hWinEventHook, event, hWnd, *)
  230.     {
  231.         try
  232.             if (WinGetTitle(hWnd) = "Snip & Sketch" && WinGetClass(hWnd) = "ApplicationFrameWindow")
  233.             {
  234.                 DllCall("UnhookWinEvent", "Ptr", hWinEventHook)
  235.                 winEventHook := 0
  236.                 WinSetTransparent(0, hWnd)
  237.                 clipPrevious := ClipboardAll()
  238.                 A_Clipboard := clipImage
  239.                 WinWait(hWnd)
  240.  
  241.                 if (!DllCall("IsClipboardFormatAvailable", "UInt", CF_BITMAP := 2)) ; Detects clipboard without image
  242.                 {
  243.                     Send("^c") ; Copies the image from Snip & Sketch in case the image didn't get saved in the clipboard
  244.                     fallbackCopyActionStartTime := A_TickCount
  245.  
  246.                     ; Waits until the clipboard has the image or times out after 2 seconds
  247.                     while (!DllCall("IsClipboardFormatAvailable", "UInt", CF_BITMAP := 2))
  248.                     {
  249.                         if (A_TickCount - fallbackCopyActionStartTime > 2000)
  250.                         {
  251.                             WinSetTransparent("Off")
  252.                             TrayTip("This fallback timed out. Resolve!", "UNABLE TO COPY SNIP", 0x12)
  253.                             SetTimer(HideTrayTip, -4000)
  254.  
  255.                             return
  256.                         }
  257.  
  258.                         Sleep(10)
  259.                     }
  260.                 }
  261.  
  262.                 WinClose()
  263.  
  264.                 ; Save clipboard image to temp folder to see its width and height (overwrites any that might've been saved in the past)
  265.                 RunWait("PowerShell.exe -Command `"$img = get-clipboard -format image; $img.save('" A_Temp "\latestSnip.jpg')`"",, "Hide")
  266.                 imageSize := GetImageSize(A_Temp "\latestSnip.jpg")
  267.  
  268.                 ; The extra space is for the paint toolset ofcourse
  269.                 rawPaintWinWidth := imageSize.Width + 27
  270.                 rawPaintWinHeight := imageSize.Height + 192
  271.  
  272.                 ; Initializing the paint wnd size (without the minimum, it will hide the paint toolset and without the maximum, it will go beyond the screen boundaries)
  273.                 paintWinWidth := (rawPaintWinWidth >= 379 ? (rawPaintWinWidth <= A_ScreenWidth ? rawPaintWinWidth : A_ScreenWidth) : 379)
  274.                 paintWinHeight := (rawPaintWinHeight >= 251 ? (rawPaintWinHeight <= A_ScreenHeight ? rawPaintWinHeight : A_ScreenHeight) : 251)
  275.  
  276.                 Run("mspaint.exe",, "Min", &paintPid)
  277.                 WinWait("ahk_pid " paintPid)
  278.                 WinSetTransparent(0)
  279.                 Send("{Ctrl down}")
  280.                 Sleep(250)
  281.  
  282.                 if (paintWinWidth = A_ScreenWidth && paintWinHeight = A_ScreenHeight)
  283.                 {
  284.                     WinMaximize() ; Some images are so big that Paint needs to be shown in a maximized state
  285.                     PasteImageAndRemoveRemainingWhiteSpace()
  286.                 }
  287.                 else
  288.                 {
  289.                     WinActivate()
  290.                     PasteImageAndRemoveRemainingWhiteSpace()
  291.                     WinRestore() ; Unmaximize if it's maximized
  292.                     WinMove((A_ScreenWidth / 2) - (paintWinWidth / 2), (A_ScreenHeight / 2) - (paintWinHeight / 2), paintWinWidth, paintWinHeight) ; Moves to center w/ new size
  293.                 }
  294.  
  295.                 WinSetTransparent("Off")
  296.                 Sleep(250)
  297.                 Send("{Shift up}{Ctrl up}")
  298.                 A_Clipboard := clipPrevious
  299.             }
  300.     }
  301.  
  302.     ; Make sure that Ctrl is down before using this fn, and release Shift and Ctrl after (using 250 ms delays might make it reliable)
  303.     PasteImageAndRemoveRemainingWhiteSpace()
  304.     {
  305.         ControlSend("v") ; Pastes the image from clipboard
  306.         Sleep(250)
  307.         Send("{Shift down}")
  308.         Sleep(250)
  309.         WinActivate()
  310.         ControlSend("x") ; Removes any white space that might remain (crops the image)
  311.     }
  312.  
  313.     GetImageSize(imagePath)
  314.     {
  315.         static shellObj := ComObject("Shell.Application")
  316.         SplitPath(imagePath, &fileName, &fileDir)
  317.         folderObj := shellObj.Namespace(fileDir)
  318.  
  319.         if (!folderItemObj := folderObj.ParseName(fileName))
  320.             throw ValueError("The image path does not contain a (valid) file", -1, imagePath)
  321.  
  322.         sizeArray := StrSplit(folderItemObj.ExtendedProperty("Dimensions"), " x ")
  323.  
  324.         ; Ad hoc object which allows you to see its properties with IntelliSense, usable w/ dot notation (image size w/o invisible characters)
  325.         return {Width: LTrim(sizeArray[1], Chr(8234)), Height: RTrim(sizeArray[2], Chr(8236))}
  326.     }
  327.  
  328.     ; This gets rid of the snip notification and its `winEventHook`, if it still exists
  329.     DismissSnipNotification(*)
  330.     {
  331.         if (winEventHook)
  332.         {
  333.             Windows.UI.Notifications.ToastNotificationManager.History.Clear("Microsoft.ScreenSketch_8wekyb3d8bbwe!App")
  334.             DllCall("UnhookWinEvent", "Ptr", winEventHook)
  335.             winEventHook := 0
  336.         }
  337.     }
  338. }
  339.  
  340. *PrintScreen::
  341. {
  342.     static latestScreenshotTime := 0
  343.     pressStartTime := A_TickCount
  344.  
  345.     loop
  346.     {
  347.         Sleep(10)
  348.  
  349.         if (!GetKeyState("PrintScreen", "P"))
  350.         {
  351.             ; PrtScn Quick-Press. This takes a new screenshot
  352.             if (A_TickCount - latestScreenshotTime > 500)
  353.             {
  354.                 Send("{Blind}{PrintScreen}") ; Blind mode allows the native Win+PrtScn hotkey to save it in the `Screenshots` folder
  355.                 latestScreenshotTime := A_TickCount
  356.  
  357.                 return
  358.             }
  359.  
  360.             ; PrtScn Double-Press. This saves the screenshot of the first press to the desktop
  361.             break
  362.         }
  363.  
  364.         ; PrtScn Long-Press. This saves any image that is currently in the clipboard to the desktop
  365.         if (A_TickCount - pressStartTime > 750)
  366.         {
  367.             if (DllCall("IsClipboardFormatAvailable", "UInt", CF_BITMAP := 2)) ; Detects a clipboard image
  368.                 break
  369.  
  370.             ToolTip("No clipboard image detected.", toolTipAxes*)
  371.             global isToolTipPrtScnShown := true
  372.             KeyWait("PrintScreen") ; Prevents the PrtScn hotkey from triggering again while it's still pressed down and for tooltip dismissal
  373.             Tooltip()
  374.             global isToolTipPrtScnShown := false
  375.  
  376.             return
  377.         }
  378.     }
  379.  
  380.     RunWait("PowerShell.exe -Command `"$img = get-clipboard -format image; $img.save('" A_Desktop "\" A_Now ".jpg')`"",, "Hide")
  381.     TrayTip("CLIPBOARD IMAGE SAVED TO DESKTOP",, 0x10)
  382.     SetTimer(HideTrayTip, -4000)
  383.     KeyWait("PrintScreen") ; Prevents the PrtScn hotkey from triggering again while it's still pressed down
  384. }
  385.  
  386. XButton1::
  387. XButton2::
  388. {
  389.     mouseEventHook.Start()
  390.     SystemCursor("Hide")
  391.     _menu := Menu()
  392.     _menu.Add("Open Google", OpenGoogle)
  393.     _menu.Add() ; seperator line
  394.     _menu.Add("Open Maps", OpenMaps)
  395.     _menu.Show(,, 0)
  396.     WinWait("ahk_class #32768 ahk_exe " A_AhkPath,, 5)
  397.     ControlSend("{Down}") ; Highlights the first menu item
  398.     MouseGetPos(, &startCursorY)
  399.     MFS_HILITE := 0x00000080
  400.     latestEventYNonZeroIncrease := 0 ; Upcoming changes will be non-zero
  401.     latestEventYNonZeroChangeAmount := 0 ; Change(s) to the first unique value are unreliable hence skipping that value
  402.  
  403.     loop
  404.     {
  405.         Sleep(50)
  406.  
  407.         if (!mouseEventHook.ProcHandle)
  408.         {
  409.             try ControlSend("{Enter}")
  410.  
  411.             return
  412.         }
  413.  
  414.         try
  415.         {
  416.             latestEventYIncreaseToProcess := startCursorY - latestMouseEvent.Y
  417.            
  418.             if (latestEventYIncreaseToProcess = 0)
  419.                 continue
  420.  
  421.             if (latestEventYIncreaseToProcess != latestEventYNonZeroIncrease)
  422.             {
  423.                 latestEventYNonZeroIncrease := latestEventYIncreaseToProcess
  424.  
  425.                 if (latestEventYNonZeroChangeAmount++ = 0)
  426.                     continue
  427.  
  428.                 menuOption1 := GetMenuItemInfo(0)
  429.                 menuOption2 := GetMenuItemInfo(2) ; Seperator line is index 1
  430.  
  431.                 if (menuOption1.FState & MFS_HILITE)
  432.                 {
  433.                     if (latestEventYNonZeroIncrease < 0)
  434.                         ControlSend("{Down}")
  435.                 }
  436.                 else if (menuOption2.FState & MFS_HILITE)
  437.                 {
  438.                     if (latestEventYNonZeroIncrease > 0)
  439.                         ControlSend("{Up}")
  440.                 }
  441.             }
  442.         }
  443.     }
  444.  
  445.     GetMenuItemInfo(index)
  446.     {
  447.         menuItem := MenuItemInfo()
  448.         menuItem.FMask := 0x00000001 ; MIIM_STATE
  449.         DllCall("GetMenuItemInfo", "Ptr", _menu.Handle, "UInt", index, "Int", true, "Ptr", menuItem)
  450.  
  451.         return menuItem
  452.     }
  453. }
  454.  
  455. XButton1 up::
  456. XButton2 up::mouseEventHook.Stop()
  457.  
  458. #HotIf (WinActive("ahk_exe notepad.exe"))
  459. MButton::WinActivate("ahk_class Progman")
  460.  
  461. #HotIf (WinActive("Visual Studio Code - Welcome ahk_exe chrome.exe"))
  462. MButton::Send("{Alt}")
  463.  
  464. #HotIf (WinActive("Microsoft Visual Studio ahk_exe devenv.exe"))
  465.  
  466. MButton::
  467. {
  468.     if ((focusedElement.Selection ?? false) && UIA.CompareElements(focusedElement.Latest, UIA.GetFocusedElement()))
  469.     {
  470.         ; Moves caret back to where it was
  471.         try focusedElement.Selection.Select()
  472.         focusedElement.Latest := unset
  473.         focusedElement.Selection := unset
  474.     }
  475.     else
  476.     {
  477.         ; Moves caret to the start of the Edit control
  478.         focusedElement.Latest := UIA.GetFocusedElement()
  479.         focusedElement.Selection := focusedElement.Latest.SelectionRange
  480.         documentRange := focusedElement.Latest.DocumentRange
  481.         documentRange.MoveEndpointByUnit(UIA.TextPatternRangeEndpoint.End, UIA.TextUnit.Document, -1)
  482.         documentRange.Select()
  483.     }
  484. }
  485.  
  486. ; Necessary to make A_ThisHotkey become one of these when pressed (HandleVisualStudioTextSelectionChangedEvent requires this)
  487. ~LButton::
  488. ~RButton::return
  489.  
  490. #HotIf (WinActive("ahk_exe uTorrent.exe"))
  491. ~RButton::
  492. {
  493.     static status := 0
  494.  
  495.     if (!status)
  496.         OnClipboardChange(HandleClipChanged, status := 1)
  497.    
  498.     HandleClipChanged(*)
  499.     {
  500.         if (WinActive("ahk_exe uTorrent.exe"))
  501.         {
  502.             HookEvent(EVENT_OBJECT_CREATE, HandleCreatedVlcEvent)
  503.             Send("+{F10}p{Enter}{Tab}"), Run(A_ProgramFiles "\VideoLAN\VLC\vlc.exe --fullscreen --aspect-ratio=16:9 " A_Clipboard)
  504.         }
  505.  
  506.         OnClipboardChange(HandleClipChanged, status := 0)
  507.  
  508.         HandleCreatedVlcEvent(hWinEventHook, event, hWnd, *)
  509.         {
  510.             static isBeingShownAfterTorrentStartsUnforced := false, WS_EX_LAYERED := 0x00080000
  511.  
  512.             try
  513.                 if (WinGetTitle(hWnd) = "VLC" && !isBeingShownAfterTorrentStartsUnforced)
  514.                 {
  515.                     isBeingShownAfterTorrentStartsUnforced := true
  516.                     try WinSetTransparent(0, hWnd)
  517.                     try WinSetEnabled(false, "ahk_exe uTorrent.exe")
  518.                     HotIf(MouseIsOverUTorrent)
  519.                     Hotkey("LButton", ShowNetworkStreamMenu, "On")
  520.                     Hotkey("RButton", ShowNetworkStreamMenu, "On")
  521.                     DllCall("UnhookWinEvent", "Ptr", hWinEventHook)
  522.                     Sleep(-1) ; Discards queued events that might remain
  523.                     WinExist(hWnd)
  524.  
  525.                     ; Waiting until VLC is full screen
  526.                     try
  527.                         loop
  528.                             if (!isBeingShownAfterTorrentStartsUnforced)
  529.                                 return
  530.                             else if (WinGetExStyle() = WS_EX_LAYERED)
  531.                                 break
  532.  
  533.                     Hotkey("LButton", "Off")
  534.                     Hotkey("RButton", "Off")
  535.                     try WinSetEnabled(true, "ahk_exe uTorrent.exe")
  536.                     try WinActivate("ahk_exe uTorrent.exe")
  537.                     try Send((ListViewGetContent("Count Focused", "SysListView322", WinExist("ahk_exe uTorrent.exe")) = 1 ? "{Down}{Up}" : "{Up}{Down}") "+{F10}s")
  538.                     try WinActivate(hWnd)
  539.                     try WinSetTransparent("Off", hWnd)
  540.                     isBeingShownAfterTorrentStartsUnforced := false
  541.                 }
  542.  
  543.             MouseIsOverUTorrent(*) => MouseIsOver("ahk_exe uTorrent.exe")
  544.  
  545.             ; This makes it possible to abort the network stream when the download speed is too low
  546.             ShowNetworkStreamMenu(*)
  547.             {
  548.                 _menu := Menu()
  549.                 _menu.Add("Abort Network Stream", AbortNetworkStream)
  550.                 _menu.Show()
  551.  
  552.                 AbortNetworkStream(*)
  553.                 {
  554.                     HotIf(MouseIsOverUTorrent)
  555.                     Hotkey("LButton", "Off")
  556.                     Hotkey("RButton", "Off")
  557.                     WinClose("ahk_exe vlc.exe")
  558.                     WinSetEnabled(true, "ahk_exe uTorrent.exe")
  559.                     WinActivate("ahk_exe uTorrent.exe")
  560.                     isBeingShownAfterTorrentStartsUnforced := false
  561.                 }
  562.             }
  563.         }
  564.     }
  565. }
  566.  
  567. #HotIf (A_TitleMatchMode := 3, MouseIsOver("Tabs Outliner ahk_exe chrome.exe")) ; TitleMatchMode 3 = exact title match (changes only the mode of the thread made for this specific #HotIf)
  568. LButton::
  569. {
  570.     static latestClickTime := 0
  571.     WinGetClientPos(&tabsOutlinerX, &tabsOutlinerY, &tabsOutlinerWidth,, "Tabs Outliner ahk_exe chrome.exe")
  572.     MouseGetPos(&cursorX, &cursorY)
  573.  
  574.     if (cursorX > tabsOutlinerX + tabsOutlinerWidth - 47 && cursorY < tabsOutlinerY + 31 && A_TickCount - latestClickTime < 3200) ; Detects close btn click w/ save likely in progress
  575.         Sleep(3200 - (A_TickCount - latestClickTime)), WinClose("Tabs Outliner ahk_exe chrome.exe") ; Delays closing the wnd long enough for any save to finish
  576.     else
  577.         Send("{LButton down}"), KeyWait("LButton"), Send("{LButton up}"), latestClickTime := A_TickCount
  578. }
  579.  
  580. #HotIf (WinActive("E-mail ahk_class Olk Host"))
  581. LButton::
  582. {
  583.     WinGetClientPos(&outlookX,, &outlookWidth)
  584.     MouseGetPos(&cursorX)
  585.  
  586.     if (MouseIsOverOutlookButton()) ; Detects minimize-, restore- or close btn click
  587.     {
  588.         ; Fixes an unresponsive click area (at the very top of the buttons) and prevents accidentally closing when you meant to minimize it
  589.         if (cursorX < outlookX + outlookWidth - 96 || cursorX > outlookX + outlookWidth - 49) ; Detects minimize- or close btn click
  590.             WinMinimize()
  591.         else if (WinGetMinMax() = 1) ; Detects maximized wnd with restore btn click
  592.             WinRestore()
  593.         else ; Detects restored down wnd with maximize btn click
  594.             WinMaximize()
  595.     }
  596.     else
  597.         Send("{LButton down}"), KeyWait("LButton"), Send("{LButton up}")
  598.  
  599.     MouseIsOverOutlookButton()
  600.     {
  601.         try return (MouseGetPos(,, &winId, &control), WinExist("E-mail ahk_class Olk Host ahk_id " winId) && (control = "WebViewCaptionButton1" || control = "WebViewCaptionButtonDepr1"))
  602.         return false
  603.     }
  604. }
  605.  
  606. #HotIf (WinActive("ahk_exe vlc.exe"))
  607. LButton::
  608. {
  609.     static fullscreenState := 2
  610.     DllCall("Shell32\SHQueryUserNotificationState", "UInt*", &monitorState := 0)
  611.  
  612.     if (monitorState != fullscreenState || monitorState = fullscreenState && WinExist("ahk_class Qt5QWindowToolTipSaveBits"))
  613.         Send("{LButton down}"), KeyWait("LButton"), Send("{LButton up}")
  614.     else
  615.         Send("{LButton}")
  616. }
  617.  
  618. #HotIf (MouseIsOver("ahk_class Shell_TrayWnd"))
  619. *LButton::
  620. {
  621.     BlockInput("MouseMove")
  622.  
  623.     if (KeyWait("LButton", "T0.5"))
  624.         Send("{LButton}"), BlockInput("MouseMoveOff")
  625.     else
  626.         Send("{LButton down}"), BlockInput("MouseMoveOff"), KeyWait("LButton"), Send("{LButton up}")
  627. }
  628.  
  629. ;********** LIBRARY **********
  630.  
  631. Initialize()
  632. {
  633.     TraySetIcon("netshell.dll", 151, true)
  634.     A_IconTip := "Time Saver"
  635.     A_CoordModeToolTip := "Screen" ; For the tooltip shown when the tray icon is clicked and also for the realtime controls tooltip
  636.     A_CoordModeMouse := "Screen" ; For the XButton hotkeys, and the LButton hotkey of the tabs outliner assist feature
  637.     A_WinDelay := -1 ; For the snip feature, HandleNameChangedThunderbirdEvent, HandleNameChangedTabsOutlinerEvent and the two different HandleCreatedVlcEvent functions
  638.     A_KeyDelay := -1 ; For the XButton hotkeys (ControlSend) and for Send b/c it reverts to the Event SendMode when another AHK script installs a native low-level keyboard/mouse hook
  639.     A_KeyDuration := 1 ; For the XButton hotkeys
  640.     EVENT_SYSTEM_FOREGROUND := 0x0003
  641.     global EVENT_OBJECT_CREATE := 0x8000
  642.     global EVENT_OBJECT_SHOW := 0x8002
  643.     EVENT_OBJECT_REORDER := 0x8004
  644.     global EVENT_OBJECT_NAMECHANGE := 0x800C
  645.     global toolTipAxes := [A_ScreenWidth * 0.75, A_ScreenHeight]
  646.     global isToolTipPrtScnShown := false
  647.     global dialog := {ShouldProcessInput: true} ; Ad hoc object, usable w/ dot notation (no need for class)
  648.     global latestMouseEvent := {Y: unset} ; Ad hoc object, usable w/ dot notation (no need for class)
  649.     global mouseEventHook := PointerDeviceHook("Move|LButton Down", HandleMouseEvent(eventInfo)
  650.     {
  651.         latestMouseEvent.Y := eventInfo.Pt.Y ; This mouse movement will be used to highlight a menu item
  652.  
  653.         return true ; Blocks both interfering mouse actions
  654.     })
  655.     global focusedElement := {Latest: unset, Selection: unset} ; Ad hoc object, usable w/ dot notation (no need for class)
  656.     global iniPath := A_ScriptFullPath
  657.     global godmodeActiveContextWindow := {HasTriggered: false}
  658.  
  659.     ; Makes tray icon merely show hotkey info on click
  660.     A_TrayMenu.Delete()
  661.     OnMessage(0x404, HandleTrayIconClick) ; 0x404 = WM_USER msg number (which can be found w/ Microsoft Spy++)
  662.  
  663.     ; Win+G opens Game Bar by default in Windows, so this will disable it (press Win and type `Game Bar settings` to enable it again)
  664.     if (RegRead("HKEY_CURRENT_USER\System\GameConfigStore", "GameDVR_Enabled"))
  665.     {
  666.         RegWrite(0, "REG_DWORD", "HKEY_CURRENT_USER\System\GameConfigStore", "GameDVR_Enabled")
  667.         RegWrite(0, "REG_DWORD", "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\GameDVR", "AppCaptureEnabled")
  668.     }
  669.  
  670.     ; PowerShell load command for HDR toggle pipe reader and status toast
  671.     hdrTogglePowershellLoadCommand := "
  672.    (
  673.        try { $pipeServer = New-Object System.IO.Pipes.NamedPipeServerStream('\\.\pipe\HdrTogglePipe') }
  674.        catch { exit } # HDR toggle Powershell process exists already
  675.        $pipeReader = New-Object System.IO.StreamReader($pipeServer)
  676.        Import-Module WindowsDisplayManager
  677.        $primaryDisplay = GetPrimaryDisplay
  678.        $toastHdrStatusScriptBlock = [System.Management.Automation.ScriptBlock]::Create(
  679.        {
  680.            param($hdrStatus)
  681.            $toastText01 = [Windows.UI.Notifications.ToastTemplateType, Windows.UI.Notifications, ContentType = WindowsRuntime]::ToastText01
  682.            $templateHdr = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]::GetTemplateContent($toastText01)
  683.            $templateHdr.SelectSingleNode('//text[@id=1]').InnerText = $hdrStatus
  684.            $toastNotifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel')
  685.            $toastNotifier.Show(($toastHdrStatus = [Windows.UI.Notifications.ToastNotification]::new($templateHdr)))
  686.            Start-Sleep -Seconds 4
  687.            $toastNotifier.Hide($toastHdrStatus)
  688.        })
  689.  
  690.        while ($true)
  691.        {
  692.            $pipeServer.WaitForConnection()
  693.            [void]$pipeReader.ReadLine()
  694.  
  695.            if ($primaryDisplay.HdrInfo.HdrEnabled)
  696.            {
  697.                $primaryDisplay.DisableHdr()
  698.                Start-Job -ScriptBlock $toastHdrStatusScriptBlock -ArgumentList 'HDR DISABLED'
  699.            }
  700.            else
  701.            {
  702.                $primaryDisplay.EnableHdr()
  703.                Start-Job -ScriptBlock $toastHdrStatusScriptBlock -ArgumentList 'HDR ENABLED'
  704.            }
  705.  
  706.            $pipeServer.Disconnect()
  707.        }
  708.    )"
  709.  
  710.     ; This silently installs the WindowsDisplayManager module one-time and loads the reliable PowerShell HDR toggle, for use with an on-demand hotkey (because Game Bar is unreliable)
  711.     try RegRead("HKEY_CURRENT_USER\SOFTWARE\Parzival\TimeSaver", "OneTimeWindowsDisplayManagerInstalled") ; Allows the catch scope to execute if the value name doesn't exist
  712.     catch
  713.     {
  714.         RegWrite(1, "REG_DWORD", "HKEY_CURRENT_USER\SOFTWARE\Parzival\TimeSaver", "OneTimeWindowsDisplayManagerInstalled")
  715.         Run("PowerShell.exe -NoExit -ExecutionPolicy Bypass -Command `"" "
  716.         (
  717.             Install-PackageProvider -Name NuGet -Scope CurrentUser -Force # Necessary for the line below
  718.             Install-Module -Name WindowsDisplayManager -Scope CurrentUser -Force -AllowClobber`n
  719.         )" hdrTogglePowershellLoadCommand "`"",, "Hide")
  720.     }
  721.     else
  722.         Run("PowerShell.exe -NoExit -ExecutionPolicy Bypass -Command `"" hdrTogglePowershellLoadCommand "`"",, "Hide")
  723.  
  724.     ; Create [ActiveContextWindows] hotkeys with the INI. This gets done first so that these WinActive hotkey variants trigger instead of any WinExist ones that are created below and any
  725.     ; that are created later when the user has added new one(s). If there are any WinExist hotkey variants that'd have triggered. Therefore, it won't matter whether I0 or I1 is used here,
  726.     ; WinExist hotkey variants won't get to trigger these and obviously can't skip them either then
  727.     if (section := IniRead(iniPath, "ActiveContextWindows"))
  728.     {
  729.         linesSplit := StrSplit(section, "`n")
  730.  
  731.         for (iteratedLine in linesSplit)
  732.             ((iteratedCommandData) => (
  733.                 HotIf((*) => WinActive(iteratedCommandData[1])),
  734.                 Hotkey("#g", (*) => HandleGodModeHotkeyActivation(() => ShellNavigate(iteratedCommandData[2])))
  735.             ))(StrSplit(iteratedLine, "="))
  736.     }
  737.  
  738.     ; Create [ExistingContextWindowPriority*] hotkeys with the INI. These use I1 to trigger any I0 WinActive hotkey variant instead that is created later when the user has added new one(s).
  739.     ; If there are any of those WinActive hotkey variant(s) that'd trigger, otherwise it'd just execute its own God Mode action
  740.     try
  741.         loop
  742.             ((iteratedCommandData) => (
  743.                 HotIf((*) => WinExist(iteratedCommandData[1])),
  744.                 Hotkey("#g", (*) => (
  745.                     Send("#g"), Sleep(100), (godmodeActiveContextWindow.HasTriggered ? Exit() : HandleGodModeHotkeyActivation(() => ShellNavigate(iteratedCommandData[2])))
  746.                 ), "I1")
  747.             ))(StrSplit(IniRead(iniPath, "ExistingContextWindowPriority" A_Index), "="))
  748.  
  749.     if (FileExist(A_ProgramFiles "\VideoLAN\VLC\vlc.exe"))
  750.     {
  751.         ; Resets fullscreen controller to the bottom center to avoid becoming stuck at the wrong position, b/c it's made immovable by a hotkey variant
  752.         IniWrite("", A_AppData "\vlc\vlc-qt-interface.ini", "FullScreen", "pos")
  753.  
  754.         try RegRead("HKEY_CURRENT_USER\SOFTWARE\Parzival\TimeSaver", "OneTimeVlcSettingChangesExecuted") ; Allows the catch scope to execute if the value name doesn't exist
  755.         catch
  756.         {
  757.             RegWrite(1, "REG_DWORD", "HKEY_CURRENT_USER\SOFTWARE\Parzival\TimeSaver", "OneTimeVlcSettingChangesExecuted")
  758.             FileCopy(A_AppData "\vlc\vlcrc", A_Temp, true) ; Backing up old settings (the other INI may contain the useful extended settings btn on the fs controller, no backup necessary)
  759.             changedVlcSettingsTrayTip := ""
  760.  
  761.             try IniRead(A_AppData "\vlc\vlc-qt-interface.ini", "MainWindow", "FSCtoolbar") ; Allows the catch scope to execute if the key doesn't exist
  762.             catch
  763.             {
  764.                 IniWrite("`"0-2;64;3;1;4;64;37;64;38;64;8;65;9-4;35-4;34;`"", A_AppData "\vlc\vlc-qt-interface.ini", "MainWindow", "FSCtoolbar")
  765.                 changedVlcSettingsTrayTip := "FscExtendedSettingsButton"
  766.             }
  767.  
  768.             for (iteratedObj in
  769.             [
  770.                 {Section: "core", Key: "fullscreen"          , Value: 1          , OccurredChange: "Fullscreen"},
  771.                 {Section: "core", Key: "custom-aspect-ratios", Value: "17:10"    , OccurredChange: "CustomAspectRatios"},
  772.                 {Section: "core", Key: "stereo-mode"         , Value: 1          , OccurredChange: "Stereo"},
  773.                 {Section: "core", Key: "volume-save"         , Value: 0          , OccurredChange: "VolumeSaveOff"},
  774.                 {Section: "core", Key: "osd"                 , Value: 0          , OccurredChange: "OsdOff"},
  775.                 {Section: "core", Key: "spu"                 , Value: 0          , OccurredChange: "SubtitlesOff"},
  776.                 {Section: "core", Key: "vout"                , Value: "direct3d9", OccurredChange: "HdrSubtitlesFix"},
  777.                 {Section: "qt"  , Key: "qt-updates-notif"    , Value: 0          , OccurredChange: "UpdatesNotifierOff"},
  778.                 {Section: "qt"  , Key: "qt-system-tray"      , Value: 0          , OccurredChange: "SystemTrayIconOff"}
  779.             ])
  780.                 try
  781.                 {
  782.                     IniRead(A_AppData "\vlc\vlcrc", iteratedObj.Section, "#" iteratedObj.Key) ; Allows the rest to execute if the commented-out default key exists
  783.                     IniWrite("`n" iteratedObj.Key "=" iteratedObj.Value, A_AppData "\vlc\vlcrc", iteratedObj.Section, "#" iteratedObj.Key)
  784.                     IniDelete(A_AppData "\vlc\vlcrc", iteratedObj.Section, "#" iteratedObj.Key)
  785.                     changedVlcSettingsTrayTip .= ", " iteratedObj.OccurredChange
  786.                 }
  787.  
  788.             ; Mentioning one-time setting changes in a persistent VLC notification
  789.             tnm := Windows.UI.Notifications.ToastNotificationManager
  790.             toastXml := tnm.GetTemplateContent("ToastText02")
  791.             toastXml.GetElementsByTagName("text").GetAt(0).InnerText := "New default settings make features usable, and prevent repetition and annoyances"
  792.             toastXml.GetElementsByTagName("text").GetAt(1).InnerText := changedVlcSettingsTrayTip
  793.             tnm.CreateToastNotifier("{6D809377-6AF0-444B-8957-A3773F02200E}\VideoLAN\VLC\vlc.exe").Show(Windows.UI.Notifications.ToastNotification(toastXml))
  794.         }
  795.     }
  796.  
  797.     ; It'll simulate native non-fullscreen taskbar functionality in the specific fullscreen windows that you set here. Unforcefully allowing the taskbar to be shown when the cursor reaches
  798.     ; the deactivated taskbar line (it won't activate the taskbar, so the taskbar retains its slide animation). Useful for non-video fullscreen windows
  799.     if (fullscreenWindowsUnhideTaskbarSection := IniRead(iniPath, "FullscreenWindowsUnhideTaskbar"))
  800.     {
  801.         linesSplit := StrSplit(StrSplit(fullscreenWindowsUnhideTaskbarSection, "`n*/")[1], "`n")
  802.  
  803.         for (iteratedLine in linesSplit)
  804.             GroupAdd("FullscreenWindows", iteratedLine)
  805.     }
  806.  
  807.     tbl := CreateTaskbarList()
  808.     outlookWinEventHook := HookEvent(EVENT_OBJECT_CREATE, HandleCreatedOutlookEvent)
  809.     HookEvent(EVENT_OBJECT_CREATE, HandleCreatedVlcEvent)
  810.     HookEvent(EVENT_OBJECT_REORDER, HandleReorderedVlcEvent)
  811.     HookEvent(EVENT_SYSTEM_FOREGROUND, HandleActivatedWindowVlcEvent)
  812.     HookEvent(EVENT_SYSTEM_FOREGROUND, HandleChangedFullscreenWinEvent)
  813.     HookEvent(EVENT_OBJECT_SHOW, HandleChangedFullscreenWinEvent)
  814.     HookEvent(EVENT_OBJECT_SHOW, HandleShowedUnsavedChangesDialogEvent)
  815.     HookEvent(EVENT_OBJECT_SHOW, HandleShowedNotificationEvent)
  816.     fullscreenVlcCloseButtonMouseEventHook := PointerDeviceHook("Move|LButton Down", HandleFullscreenVlcCloseButtonMouseEvent, true)
  817.  
  818.     for (iteratedApp in ComObject("Shell.Application").NameSpace("shell:Appsfolder").Items)
  819.         if (iteratedApp.Name = "ยตTorrent")
  820.             SetTimer(UnfocusUTorrent, -1)
  821.  
  822.     if (ProcessExist("olk.exe")) ; Prevents opening multiple Outlook instances when Time Saver reloads (also no need to auto-run it minimized if the user had already opened it)
  823.         DllCall("UnhookWinEvent", "Ptr", outlookWinEventHook)
  824.     else
  825.     {
  826.         A_DetectHiddenWindows := true
  827.  
  828.         ; This will wait on `Minimized Tabs Outliner.ahk` to have detected Tabs Outliner, if that script is being used as well (allows that script to keep a lower timeout and finish faster)
  829.         if (WinExist("Minimized Tabs Outliner.ahk"))
  830.         {
  831.             GroupAdd("TabsOutliner", "_crx_eggkanocgddhmamlbiijnphhppkpkmkl")
  832.             GroupAdd("TabsOutliner", "Tabs Outliner ahk_exe chrome.exe")
  833.             WinWait("ahk_group TabsOutliner",, 30)
  834.         }
  835.  
  836.         A_DetectHiddenWindows := false
  837.         Run("olk.exe",, "Max") ; Runs Outlook
  838.     }
  839.  
  840.     ManageVisualStudioEventHandlers() ; Has a loop, so keep this at the bottom
  841.  
  842.     HandleTrayIconClick(wParam, lParam, *)
  843.     {
  844.         static WM_LBUTTONUP := 0x0202, WM_RBUTTONUP := 0x0205
  845.  
  846.         if (lParam = WM_LBUTTONUP || lParam = WM_RBUTTONUP)
  847.         {
  848.             ToolTip("๐—›๐—ข๐—ง๐—ž๐—˜๐—ฌ ๐—œ๐—ก๐—™๐—ข`n"
  849.                 "โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”`n"
  850.                 "๐—ฃ๐—ฎ๐˜‚๐˜€๐—ฒ = MEDIA CONTROL`n"
  851.                 "๐—ช๐—ถ๐—ป+๐—š = GOD MODE`n"
  852.                 "๐—ช๐—ถ๐—ป+๐—ฅ = SMART RUN`n"
  853.                 "๐—ช๐—ถ๐—ป+๐—– = CALC/CTRL`n"
  854.                 "๐—ช๐—ถ๐—ป+๐—ฆ = SNIP`n"
  855.                 "๐—ฃ๐—ฟ๐˜๐—ฆ๐—ฐ๐—ป = SCREENSHOT+`n"
  856.                 "๐—ซ๐—•๐˜‚๐˜๐˜๐—ผ๐—ป* = MOUSE MENU`n"
  857.                 "๐— ๐—•๐˜‚๐˜๐˜๐—ผ๐—ป = CONCEAL CARET")
  858.  
  859.             ; This removes the tooltip whether modifiers are used or not, and allows hotkey variants to remain functional without them preventing the tooltip removal
  860.             (mouseEventHook := PointerDeviceHook("LButton Down|RButton Down", HandleMouseEvent)).Start()
  861.             HandleMouseEvent(*) => (ToolTip(), mouseEventHook.Stop())
  862.         }
  863.     }
  864.  
  865.     CreateTaskbarList()
  866.     {
  867.         iid_ITaskbarList := "{56FDF342-FD6D-11d0-958A-006097C9A090}" ; Interface id (iid)
  868.         clsid_TaskbarList := "{56FDF344-FD6D-11d0-958A-006097C9A090}" ; Class id (clsid)
  869.         tbl := ComObject(clsid_TaskbarList, iid_ITaskbarList) ; Creates the TaskbarList object
  870.  
  871.         loop (10)
  872.         {
  873.             try ComCall(3, tbl) ; Calls tbl.HrInit(), which initializes the TaskbarList object
  874.             catch
  875.                 Sleep(50)
  876.             else
  877.                 break
  878.         }
  879.  
  880.         return tbl
  881.     }
  882.  
  883.     HandleCreatedOutlookEvent(hWinEventHook, event, hWnd, *)
  884.     {
  885.         static outlookIsBeingLoaded := false
  886.  
  887.         ; Most windowing functions that are given a pure HWND will also work while it's hidden (dunno if it matters here but still)
  888.         try shouldExecute := WinGetClass(hWnd) = "Olk Host" && !outlookIsBeingLoaded
  889.  
  890.         if (shouldExecute ?? false)
  891.         {
  892.             outlookIsBeingLoaded := true
  893.             WinSetTransparent(0, hWnd)
  894.             ComCall(5, tbl, "Ptr", hWnd) ; Calls tbl.DeleteTab(winId), which deletes a tab from the TaskbarList
  895.             DllCall("UnhookWinEvent", "Ptr", hWinEventHook)
  896.             WinWait("- Outlook ahk_exe olk.exe") ; Minimum delay for the minimize to work
  897.             Sleep(2500) ; Extra delay to make sure that outlook has fully loaded before minimizing it and then outlook won't have to load once the user activates it
  898.             WinMinimize(hWnd)
  899.             WinSetTransparent("Off", hWnd)
  900.             ComCall(4, tbl, "Ptr", hWnd) ; Calls tbl.AddTab(winId), which adds a tab to the TaskbarList
  901.         }
  902.     }
  903.  
  904.     HandleCreatedVlcEvent(hWinEventHook, event, hWnd, *)
  905.     {
  906.         static isAttemptingToChangeAspectRatio := false
  907.  
  908.         try
  909.             if (!isAttemptingToChangeAspectRatio && WinGetProcessName(hWnd) = "vlc.exe" && WinGetClass(hWnd) = "Qt5QWindowIcon" && WinGetTitle(hWnd) != "Building font cache")
  910.             {
  911.                 isAttemptingToChangeAspectRatio := true
  912.                 Sleep(400) ; Discards queued events that might remain, and allows VLC to both update its INI and fully load (necessary for the INI fn below to change VLC's aspect ratio)
  913.  
  914.                 if (DetermineIsPlayingFromAspectRatioVideosContextFolder())
  915.                     Send("a")
  916.  
  917.                 isAttemptingToChangeAspectRatio := false
  918.             }
  919.  
  920.         DetermineIsPlayingFromAspectRatioVideosContextFolder()
  921.         {
  922.             playedMedia := IniRead(A_AppData "\vlc\vlc-qt-interface.ini", "RecentsMRL", "list")
  923.  
  924.             ; This detects a network stream from Popcorn Time to VLC (the uTorrent feature won't trigger a match, it uses the --aspect-ratio flag instead which is 100% reliable)
  925.             if (playedMedia ~= "^http://127.0.0.1:") ; The ^ requires the match to be at the start
  926.                 return true
  927.  
  928.             ; https://www.autohotkey.com/docs/alpha/misc/RegEx-QuickRef.htm (Regular Expressions [RegEx] - Quick Reference)
  929.             loop parse (StrReplace(IniRead(A_ScriptFullPath, "AspectRatioVideosContextFolders"), " ", "%20")), "`n"
  930.                 if (playedMedia ~= "^file:///" A_LoopField) ; The ^ requires the match to be at the start
  931.                     return true
  932.  
  933.             return false
  934.         }
  935.     }
  936.  
  937.     ; Toggles custom VLC close btn feature when VLC becomes active/inactive
  938.     HandleActivatedWindowVlcEvent(*)
  939.     {
  940.         static isManagingCustomCloseButton := false
  941.  
  942.         if (WinActive("ahk_exe vlc.exe"))
  943.         {
  944.             if (!IsSet(fullscreenVlcCloseButtonGui) && !isManagingCustomCloseButton)
  945.             {
  946.                 ; Loading custom fadeable close btn for in fullscreen VLC (which is almost identical to its native close btn)
  947.                 isManagingCustomCloseButton := true
  948.                 global fullscreenVlcCloseButtonGui := Gui("+AlwaysOnTop -Caption")
  949.                 fullscreenVlcCloseButtonGui.BackColor := "E81123"
  950.                 fullscreenVlcCloseButtonGui.SetFont("s11", "Comic Sans MS")
  951.                 fullscreenVlcCloseButtonGui.AddText("x16 y0 cWhite Center", "X") ; Skipped .OnEvent("Click", ..) b/c it requires `x0 y0 w47`
  952.                 WinSetTransparent(0, fullscreenVlcCloseButtonGui)
  953.                 WinSetExStyle("+0x08000000L", fullscreenVlcCloseButtonGui) ; Adds WS_EX_NOACTIVATE
  954.                 fullscreenVlcCloseButtonGui.Show("x" A_ScreenWidth - 47 " y0 w45 h21 NoActivate")
  955.                 global fullscreenVlcCloseButtonFadeState := "FadedOut"
  956.                 fullscreenVlcCloseButtonMouseEventHook.Start()
  957.                 isManagingCustomCloseButton := false
  958.             }
  959.         }
  960.         else if (IsSet(fullscreenVlcCloseButtonGui) && !isManagingCustomCloseButton)
  961.         {
  962.             isManagingCustomCloseButton := true
  963.             fullscreenVlcCloseButtonMouseEventHook.Stop()
  964.             WinClose(fullscreenVlcCloseButtonGui)
  965.             global fullscreenVlcCloseButtonGui := unset
  966.             isManagingCustomCloseButton := false
  967.         }
  968.     }
  969.  
  970.     ; Hides custom VLC close btn when the user goes out of fullscreen while it's visible
  971.     HandleReorderedVlcEvent(*)
  972.     {
  973.         static fullscreenState := 2
  974.  
  975.         if (WinActive("ahk_exe vlc.exe"))
  976.         {
  977.             DllCall("Shell32\SHQueryUserNotificationState", "UInt*", &monitorState := 0)
  978.  
  979.             if (monitorState != fullscreenState && IsSet(fullscreenVlcCloseButtonFadeState) && fullscreenVlcCloseButtonFadeState = "FadedIn")
  980.             {
  981.                 try WinSetTransparent(0, fullscreenVlcCloseButtonGui)
  982.                 global fullscreenVlcCloseButtonFadeState := "FadedOut"
  983.             }
  984.         }
  985.     }
  986.  
  987.     HandleFullscreenVlcCloseButtonMouseEvent(eventInfo)
  988.     {
  989.         static fullscreenState := 2, latestButtonUsageTime := 0
  990.         DllCall("Shell32\SHQueryUserNotificationState", "UInt*", &monitorState := 0)
  991.  
  992.         ; Click is instant and desktop is fullscreen, so this MouseEvent handler shouldn't execute after the click closed VLC, before the WinEvent is handled (hence the 2nd condition)
  993.         if (monitorState != fullscreenState || !WinActive("ahk_exe vlc.exe"))
  994.             return
  995.  
  996.         if (eventInfo.Pt.X > A_ScreenWidth - 48 && eventInfo.Pt.Y < 21) ; Hovering the close btn
  997.         {
  998.             if (eventInfo.Action = "Move")
  999.             {
  1000.                 if (fullscreenVlcCloseButtonFadeState = "FadedOut")
  1001.                 {
  1002.                     global fullscreenVlcCloseButtonFadeState := "Fading"
  1003.  
  1004.                     ; Using a timer allows the fade-in to finish while the close btn waits for release in the click state
  1005.                     SetTimer(FadeInVlcCloseButton()
  1006.                     {
  1007.                         static opacity := 0
  1008.  
  1009.                         try
  1010.                         {
  1011.                             if ((opacity += 25) >= 255)
  1012.                             {
  1013.                                 WinSetTransparent("Off", fullscreenVlcCloseButtonGui), SetTimer(, 0), opacity := 0
  1014.                                 global fullscreenVlcCloseButtonFadeState := "FadedIn"
  1015.                             }
  1016.                             else
  1017.                                 WinSetTransparent(opacity, fullscreenVlcCloseButtonGui)
  1018.                         }
  1019.                         catch
  1020.                             SetTimer(, 0), opacity := 0
  1021.                     }, 10)
  1022.                 }
  1023.             }
  1024.             else if (latestButtonUsageTime != eventInfo.KeyUsageTime) ; And when LButton is being pressed down
  1025.             {
  1026.                 latestButtonUsageTime := eventInfo.KeyUsageTime
  1027.                 fullscreenVlcCloseButtonGui.BackColor := "F1707A"
  1028.                 fullscreenVlcCloseButtonMouseEventHook.Stop()
  1029.                 KeyWait("LButton")
  1030.                 try WinClose("ahk_class Qt5QWindowIcon ahk_exe vlc.exe")
  1031.                 global fullscreenVlcCloseButtonFadeState := "FadedOut"
  1032.             }
  1033.         }
  1034.         else if (eventInfo.Action = "Move" && fullscreenVlcCloseButtonFadeState = "FadedIn")
  1035.         {
  1036.             global fullscreenVlcCloseButtonFadeState := "Fading"
  1037.  
  1038.             loop (255)
  1039.                 WinSetTransparent(255 - A_Index, fullscreenVlcCloseButtonGui), A_Index += 25, Sleep(10)
  1040.  
  1041.             WinSetTransparent(0, fullscreenVlcCloseButtonGui)
  1042.             global fullscreenVlcCloseButtonFadeState := "FadedOut"
  1043.         }
  1044.     }
  1045.  
  1046.     HandleShowedUnsavedChangesDialogEvent(hWinEventHook, event, hWnd, *)
  1047.     {
  1048.         if (WinExist("ahk_class #32770 ahk_id " hWnd))
  1049.         {
  1050.             try WinActivate(DllCall("GetParent", "UInt", hWnd))
  1051.             try WinActivate()
  1052.         }
  1053.     }
  1054.  
  1055.     HandleChangedFullscreenWinEvent(hWinEventHook, event, hWnd, *)
  1056.     {
  1057.         static fullscreenState := 2
  1058.  
  1059.         if (WinExist("ahk_group FullscreenWindows ahk_id " hWnd))
  1060.         {
  1061.             startTime := A_TickCount
  1062.  
  1063.             ; Repeats atleast 30 times to unmark as early as possible at an unknown repetition (the exact moment can't be determined, that would've been the only other way)
  1064.             while (A_TickCount - startTime < 500)
  1065.             {
  1066.                 DllCall("Shell32\SHQueryUserNotificationState", "UInt*", &monitorState := 0)
  1067.  
  1068.                 if (monitorState != fullscreenState)
  1069.                     continue
  1070.  
  1071.                 MarkFullscreenWindow(hWnd, false)
  1072.                 DllCall("Sleep", "UInt", 10) ; This DllCall workaround prevents queued events from being handled in the meantime
  1073.  
  1074.                 if (A_TickCount - startTime > 300)
  1075.                     return
  1076.             }
  1077.         }
  1078.  
  1079.         ; https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist2-markfullscreenwindow
  1080.         MarkFullscreenWindow(hWnd := WinExist("A"), fullscreenStatusToSet := true)
  1081.         {
  1082.             static tbl2 := CreateTaskbarList2()
  1083.             ComCall(8, tbl2, "Ptr", hWnd, "Int", fullscreenStatusToSet)
  1084.  
  1085.             CreateTaskbarList2()
  1086.             {
  1087.                 iid_ITaskbarList2 := "{602D4995-B13A-429B-A66E-1935E44F4317}" ; Interface id (iid)
  1088.    
  1089.                 return ComObjQuery(tbl, iid_ITaskbarList2) ; Queries the TaskbarList object to get the TaskbarList2 object
  1090.             }
  1091.         }
  1092.     }
  1093.  
  1094.     HandleShowedNotificationEvent(hWinEventHook, event, hWnd, *)
  1095.     {
  1096.         ; One WinRAR wnd has the title used below (permanently ofcourse) and has `ahk_class #32770`, while the other WinRAR wnd has the class used below and has temporary title `WinRAR`.
  1097.         ; The Software Ideas Modeler wnd has no unique title nor class at any point but it does have a control with the text used below
  1098.         try
  1099.             if
  1100.             (
  1101.                 WinGetTitle(hWnd) = "Please purchase WinRAR license" || (WinGetClass(hWnd) = "RarReminder" && WinGetProcessName(hWnd) = "WinRAR.exe") ||
  1102.                 ControlGetText("WindowsForms10.STATIC.app.0.2bf8098_r8_ad12", hWnd) = "Thank you for using Software Ideas Modeler!"
  1103.             )
  1104.                 WinSetTransparent(0, hWnd), WinClose(hWnd)
  1105.     }
  1106.  
  1107.     ; With Alt+Esc you can cycle open windows, but uTorrent gets that focus automatically at startup so this will unfocus it (e.g. prevents <Enter> from activating it)
  1108.     UnfocusUTorrent()
  1109.     {
  1110.         static WS_CAPTION := 0xC00000 ; title bar
  1111.  
  1112.         if (!WinActive("ahk_exe uTorrent.exe"))
  1113.         {
  1114.             SetTimer(, -1)
  1115.  
  1116.             return
  1117.         }
  1118.  
  1119.         for (iteratedId in WinGetList())
  1120.             if (WinExist(iteratedId) && !WinActive() && WinGetMinMax() != -1 && (WinGetClass() = "Progman" ? true : WinGetStyle() & WS_CAPTION) && WinGetTitle() != "")
  1121.                 break
  1122.  
  1123.         WinActivate()
  1124.     }
  1125.  
  1126.     ManageVisualStudioEventHandlers()
  1127.     {
  1128.         static textSelectionChangedEventHandler := UIA.CreateAutomationEventHandler(HandleVisualStudioTextSelectionChangedEvent)
  1129.             , structureChangedEventHandler := UIA.CreateStructureChangedEventHandler(HandleVisualStudioStructureChangedEvent)
  1130.             , cacheRequest := UIA.CreateCacheRequest(["Type", "ClassName"],, UIA.TreeScope.Element)
  1131.  
  1132.         loop
  1133.         {
  1134.             WinWaitActive("Microsoft Visual Studio ahk_exe devenv.exe")
  1135.  
  1136.             loop
  1137.             {
  1138.                 try
  1139.                 {
  1140.                     visualStudioElement := UIA.ElementFromHandle("Microsoft Visual Studio ahk_exe devenv.exe")
  1141.  
  1142.                     break
  1143.                 }
  1144.                 catch
  1145.                     Sleep(100)
  1146.             }
  1147.  
  1148.             UIA.AddAutomationEventHandler(textSelectionChangedEventHandler, visualStudioElement, UIA.Event.Text_TextSelectionChanged)
  1149.             UIA.AddStructureChangedEventHandler(structureChangedEventHandler, visualStudioElement,, cacheRequest)
  1150.             WinWaitNotActive() ; To make it work with multiple VS windows, it'll remove the event handlers on deactivate, and event handlers are natively removed on close
  1151.             try UIA.RemoveAutomationEventHandler(UIA.Event.Text_TextSelectionChanged, visualStudioElement, textSelectionChangedEventHandler)
  1152.             UIA.RemoveStructureChangedEventHandler(structureChangedEventHandler, visualStudioElement)
  1153.         }
  1154.  
  1155.         ; Reset caret hide state on relevant text selection
  1156.         HandleVisualStudioTextSelectionChangedEvent(element, *)
  1157.         {
  1158.             try (A_ThisHotkey != "MButton" && UIA.CompareElements(focusedElement.Latest, element)) ? (focusedElement.Latest := unset, focusedElement.Selection := unset) : Exit()
  1159.         }
  1160.  
  1161.         ; Auto-scroll namespace on relevant structure change
  1162.         HandleVisualStudioStructureChangedEvent(sender, changeType, *)
  1163.         {
  1164.             ; Only StructureChangeType_ChildAdded is allowed to continue
  1165.             if (changeType != 0)
  1166.                 return
  1167.  
  1168.             if (sender.CachedType != UIA.Type.Pane || sender.CachedClassName != "ViewPresenter")
  1169.                 return
  1170.  
  1171.             for (iteratedEditControl in sender.FindElements({Type: "Edit"}))
  1172.             {
  1173.                 try namespaceTextRange := iteratedEditControl.DocumentRange.FindText("namespace")
  1174.  
  1175.                 ; The bounding rectangles obj exists only in the returned array when the text range is near the top, but also has properties (X, Y, W, H) that you can technically use
  1176.                 if (IsSet(namespaceTextRange) && namespaceTextRange.GetBoundingRectangles().Length = 1)
  1177.                     namespaceTextRange.ScrollIntoView(1)
  1178.             }
  1179.         }
  1180.     }
  1181. }
  1182.  
  1183. HandleGodModeHotkeyActivation(shellNavigateFnObj)
  1184. {
  1185.     static isActive := false
  1186.  
  1187.     ; Keeps other godmode hotkey variants from running while there's already one active and also won't execute if the user has turned Game Bar back on, because it uses the same hotkey
  1188.     if (isActive && RegRead("HKEY_CURRENT_USER\System\GameConfigStore", "GameDVR_Enabled"))
  1189.         return
  1190.  
  1191.     isActive := true
  1192.     pressStartTime := A_TickCount
  1193.  
  1194.     ; Holding Win+G pressed down for 2sec will attempt to add the active context window along with a File Explorer window to the INI
  1195.     loop
  1196.     {
  1197.         Sleep(10)
  1198.  
  1199.         if (!GetKeyState("#", "P") && !GetKeyState("g", "P"))
  1200.             break
  1201.  
  1202.         if (A_TickCount - pressStartTime > 2000)
  1203.         {
  1204.             detectedFolderPath := DetermineAnyShellFolderWinExist(&locationName)
  1205.  
  1206.             if (detectedFolderPath = "")
  1207.                 MsgBox("To save a special File Explorer window such as the Control Panel or the Recycle Bin as the Win+G destination folder; "
  1208.                     "first activate it, then the Win+G context window and lastly keep Win+G pressed for 2 seconds. "
  1209.                     "For special destinations that are not inside File Explorer, then use the (advanced) input box by pressing the Win+G hotkey three times."
  1210.                     , "No Open Folder Detected! - God Mode", 0x40000)
  1211.             else
  1212.             {
  1213.                 IniWriteSectionOfChoice(WinGetProcessName("A"), detectedFolderPath)
  1214.                 TrayTip("Destination:`t" locationName, "GOD MODE CONTEXT WND ADDED TO INI", 0x10)
  1215.                 SetTimer(HideTrayTip, -4000)
  1216.                 KeyWait("LWin") ; Prevents the godmode hotkey variant from triggering again while it's still pressed down
  1217.                 isActive := false
  1218.             }
  1219.  
  1220.             return
  1221.         }
  1222.     }
  1223.  
  1224.     HandleHotkeyActivation(shellNavigateFnObj, DoublePressAction, TriplePressAction)
  1225.     isActive := false
  1226.  
  1227.     ; This lets you select a destination folder
  1228.     DoublePressAction()
  1229.     {
  1230.         dialog.ShouldProcessInput := true
  1231.         HotIf(MouseIsOverCancelButton)
  1232.         Hotkey("~*LButton", (*) => dialog.ShouldProcessInput := false, "On")
  1233.         HookEvent(EVENT_OBJECT_SHOW, HandleShowedDialogEvent)
  1234.         selectedFolder := FileSelect("D", "shell:MyComputerFolder\", "Select folder as destination to be reached with Win+G and context window")
  1235.         Hotkey("~*LButton", "Off")
  1236.  
  1237.         if (dialog.ShouldProcessInput)
  1238.         {
  1239.             if (selectedFolder = "")
  1240.                 MsgBox("To save a special File Explorer window such as the Control Panel or the Recycle Bin as the Win+G destination folder; "
  1241.                     "first activate it, then the Win+G context window and lastly keep Win+G pressed for 2 seconds. "
  1242.                     "For special destinations that are not inside File Explorer, then use the (advanced) input box by pressing the Win+G hotkey three times."
  1243.                     , "No Folder Selection Detected! - God Mode", 0x40000)
  1244.             else
  1245.                 IniWriteSectionOfChoice(WinGetProcessName("A"), selectedFolder)
  1246.         }
  1247.  
  1248.         ; Disables dialog close button and makes window stay always-on-top (the user should use the cancel button instead b/c it won't show a msg when there is no folder selected)
  1249.         HandleShowedDialogEvent(hWinEventHook, event, hWnd, *)
  1250.         {
  1251.             try
  1252.                 if (WinGetClass(hWnd) = "#32770")
  1253.                 {
  1254.                     DllCall("UnhookWinEvent", "Ptr", hWinEventHook)
  1255.                     DllCall("EnableMenuItem", "Ptr", DllCall("GetSystemMenu", "UInt", hWnd, "Int", 0), "UInt", SC_CLOSE := 0xF060, "UInt", MF_GRAYED := 0x00000001)
  1256.                     WinSetAlwaysOnTop(true, hWnd)
  1257.                 }
  1258.         }
  1259.  
  1260.         MouseIsOverCancelButton(*)
  1261.         {
  1262.             try return (MouseGetPos(,, &winId, &control), WinExist("ahk_class #32770 ahk_id " winId) && control = "Button2")
  1263.             return false
  1264.         }
  1265.     }
  1266.  
  1267.     ; Advanced: input box for special destination (e.g. https://youtube.com to open YouTube in your browser or shell folder shortcuts such as shell:AppsFolder)
  1268.     TriplePressAction()
  1269.     {
  1270.         static _gui
  1271.  
  1272.         if (IsSet(_gui))
  1273.             _gui.Show()
  1274.         else
  1275.         {
  1276.             _gui := Gui("+AlwaysOnTop -SysMenu", "Advanced Dialog - God Mode")
  1277.             _gui.BackColor := "White"
  1278.             _gui.AddText(, "`nEnter destination to be reached with Win+G and context window`n")
  1279.             _gui.AddEdit("vDestination w340 h23")
  1280.             _gui.AddButton("default w88 h26 x170 y107", "OK").OnEvent("Click", ProcessUserInput)
  1281.             _gui.AddButton("w88 h26 x+7 y107", "Cancel").OnEvent("Click", (*) => _gui.Hide())
  1282.             _gui.AddProgress("w360 h61 x0 y89 cF0F0F0", 100)
  1283.             _gui.AddButton("w88 h26 x170 y107", "OK") ; Gray bg btn overlay
  1284.             _gui.AddButton("w88 h26 x+7 y107", "Cancel") ; Gray bg btn overlay
  1285.             _gui.Show("w360 h150")
  1286.         }
  1287.  
  1288.         ProcessUserInput(*)
  1289.         {
  1290.             if ((destination := _gui.Submit().Destination) != "")
  1291.                 IniWriteSectionOfChoice(WinGetProcessName("A"), destination)
  1292.         }
  1293.     }
  1294.  
  1295.     IniWriteSectionOfChoice(contextWindow, destination)
  1296.     {
  1297.         HookEvent(EVENT_OBJECT_CREATE, HandleCreatedDialogEvent)
  1298.         shouldAddToSectionExistingContextWindowPriorityN := MsgBox("The following context window will be used:`t" contextWindow
  1299.             "`n`nClick `"Exist`" if the context window has to exist before it may trigger on hotkey press. It will then have the next available priority, "
  1300.             "so when there is more than one of these context windows existing, whichever has the highest priority gets triggered. Otherwise click "
  1301.             "`"Active`" if the context window has to be active", "Context Window Condition - God Mode", 0x40004)
  1302.  
  1303.         if (shouldAddToSectionExistingContextWindowPriorityN = "Yes")
  1304.         {
  1305.             IniWriteExistingContextWindows("ahk_exe " contextWindow "=" destination)
  1306.             HotIf((*) => WinExist("ahk_exe " contextWindow))
  1307.             Hotkey("#g", (*) => (Send("#g"), Sleep(100), (godmodeActiveContextWindow.HasTriggered ? Exit() : HandleGodModeHotkeyActivation(() => ShellNavigate(destination)))), "I1")
  1308.         }
  1309.         else
  1310.         {
  1311.             IniWrite(destination, iniPath, "ActiveContextWindows", "ahk_exe " contextWindow)
  1312.             HotIf((*) => WinActive("ahk_exe " contextWindow))
  1313.             Hotkey("#g", (*) => (
  1314.                 HandleGodModeHotkeyActivation(() => ShellNavigate(destination)),
  1315.                 godmodeActiveContextWindow.HasTriggered := true,
  1316.                 SetTimer(() => godmodeActiveContextWindow.HasTriggered := false, -100)
  1317.             ))
  1318.         }
  1319.  
  1320.         HandleCreatedDialogEvent(hWinEventHook, event, hWnd, *)
  1321.         {
  1322.             try
  1323.                 if (WinGetClass(hWnd) = "#32770")
  1324.                 {
  1325.                     DllCall("UnhookWinEvent", "Ptr", hWinEventHook)
  1326.                     ControlSetText("Exist", "Button1", hWnd)
  1327.                     ControlSetText("Active", "Button2", hWnd)
  1328.                 }
  1329.         }
  1330.     }
  1331. }
  1332.  
  1333. HideTrayTip()
  1334. {
  1335.     TrayTip() ; Attempt to hide it the normal way
  1336.  
  1337.     if (SubStr(A_OSVersion, 1, 3) = "10.")
  1338.         A_IconHidden := true, Sleep(200), A_IconHidden := false
  1339. }
  1340.  
  1341. ; Detects single, double, and triple-presses of a hotkey. This allows a hotkey to perform a different operation depending on how many times you press it (convenient encapsulation only)
  1342. HandleHotkeyActivation(onePressActionFnObj, doublePressActionFnObj, triplePressActionFnObj?)
  1343. {
  1344.     static quickPressCount := 0, _executeMultiFunctionHotkeyAction
  1345.     maxPressCount := IsSet(triplePressActionFnObj) ? 3 : 2
  1346.  
  1347.     if (quickPressCount + 1 < maxPressCount)
  1348.         ++quickPressCount
  1349.     else
  1350.     {
  1351.         quickPressCount := maxPressCount
  1352.  
  1353.         return
  1354.     }
  1355.  
  1356.     if (!IsSet(_executeMultiFunctionHotkeyAction))
  1357.         _executeMultiFunctionHotkeyAction := ExecuteMultiFunctionHotkeyAction ; Allows timer updates
  1358.  
  1359.     SetTimer(_executeMultiFunctionHotkeyAction, -500)
  1360.  
  1361.     ExecuteMultiFunctionHotkeyAction()
  1362.     {
  1363.         switch (quickPressCount)
  1364.         {
  1365.             case 1: onePressActionFnObj()
  1366.             case 2: doublePressActionFnObj()
  1367.             case 3: triplePressActionFnObj()
  1368.         }
  1369.  
  1370.         quickPressCount := 0
  1371.         _executeMultiFunctionHotkeyAction := unset
  1372.     }
  1373. }
  1374.  
  1375. ; This writes a new section below [ExistingContextWindows] or the latest [ExistingContextWindowPriorityN] if there are any (the new section can be part of godmode but custom too!)
  1376. IniWriteExistingContextWindows(pairs, section?)
  1377. {
  1378.     loop
  1379.     {
  1380.         try IniRead(iniPath, "ExistingContextWindowPriority" A_Index) ; Allows the catch scope to execute if the key doesn't exist
  1381.         catch
  1382.         {
  1383.             if (!IsSet(section))
  1384.                 section := "[ExistingContextWindowPriority" A_Index "]"
  1385.  
  1386.             IniWrite("`n" section "`n" pairs, iniPath, A_Index = 1 ? "ExistingContextWindows" : "ExistingContextWindowPriority" A_Index - 1, "[TemporarySection]")
  1387.             IniDelete(iniPath, "TemporarySection")
  1388.  
  1389.             break
  1390.         }
  1391.     }
  1392. }
  1393.  
  1394. ShellNavigate(path)
  1395. {
  1396.     static shellObj := ComObject("Shell.Application")
  1397.  
  1398.     if
  1399.     (
  1400.         InStr(path, "chrome.exe") &&
  1401.         !ProcessExist("chrome.exe") &&
  1402.         (hasTabsOutlinerExtension := DirExist(EnvGet("LocalAppData") "\Google\Chrome\User Data\Default\Extensions\eggkanocgddhmamlbiijnphhppkpkmkl"))
  1403.     )
  1404.         HookEvent(EVENT_OBJECT_NAMECHANGE, HandleNameChangedTabsOutlinerEvent)
  1405.  
  1406.     ; Shows search field after it runs an AHK site (the initial delay is in case such a chrome window exists already, to affect the new tab when it has fully loaded after the 2nd delay)
  1407.     if (InStr(path, "autohotkey.com"))
  1408.     {
  1409.         Run(path)
  1410.         Sleep(500)
  1411.  
  1412.         if (WinWaitActive("AutoHotkey v2",, 15))
  1413.             Sleep(500), Send("!s")
  1414.  
  1415.         return
  1416.     }
  1417.  
  1418.     ; The first scope can change the active explorer window location (prevents unnecessarily opening another explorer window), but it can run all kinds of stuff just like the Run command
  1419.     if ((activeWinId := WinActive("ahk_class CabinetWClass")) || (activeWinId := WinActive("ahk_class ExploreWClass")))
  1420.     {
  1421.         for (iteratedWindow in shellObj.Windows)
  1422.             if ((activeWindow := iteratedWindow).hWnd = activeWinId)
  1423.                 break
  1424.  
  1425.         ; Adding the shell: prefix to CLSIDs that do not have it already (to make them compatible with the Navigate2 fn)
  1426.         if (SubStr(path, 1, 3) = "::{")
  1427.             path := "shell:" path
  1428.  
  1429.         activeWindow.Navigate2(path)
  1430.     }
  1431.     else
  1432.         Run(path)
  1433. }
  1434.  
  1435. DetermineAnyShellFolderWinExist(&locationName?)
  1436. {
  1437.     static shellObj := ComObject("Shell.Application")
  1438.  
  1439.     if ((latestActiveWinId := WinExist("ahk_class CabinetWClass")) || (latestActiveWinId := WinExist("ahk_class ExploreWClass")))
  1440.     {
  1441.         for (iteratedWindow in shellObj.Windows)
  1442.             if ((latestActiveWindow := iteratedWindow).hWnd = latestActiveWinId)
  1443.                 break
  1444.  
  1445.         locationName := latestActiveWindow.LocationName
  1446.  
  1447.         return latestActiveWindow.Document.Folder.Self.Path
  1448.     }
  1449. }
  1450.  
  1451. ; Argument can be Show, Hide, Toggle or Reload
  1452. SystemCursor(cmd)
  1453. {
  1454.     static visible := true, c := Map()
  1455.     static sys_cursors := [32512, 32513, 32514, 32515, 32516, 32642, 32643, 32644, 32645, 32646, 32648, 32649, 32650]
  1456.  
  1457.     if (cmd = "Reload" || !c.Count) ; Reload when requested or at first call
  1458.     {
  1459.         for (i, id in sys_cursors)
  1460.         {
  1461.             h_cursor  := DllCall("LoadCursor", "Ptr", 0, "Ptr", id)
  1462.             h_default := DllCall("CopyImage", "Ptr", h_cursor, "UInt", 2, "Int", 0, "Int", 0, "UInt", 0)
  1463.             h_blank   := DllCall("CreateCursor", "Ptr", 0, "Int", 0, "Int", 0, "Int", 32, "Int", 32, "Ptr", Buffer(32 * 4, 0xFF), "Ptr", Buffer(32 * 4, 0))
  1464.             c[id] := {Default: h_default, Blank: h_blank}
  1465.         }
  1466.     }
  1467.  
  1468.     switch (cmd)
  1469.     {
  1470.         case "Show": visible := true
  1471.         case "Hide": visible := false
  1472.         case "Toggle": visible := !visible
  1473.         default: return
  1474.     }
  1475.  
  1476.     for (id, handles in c)
  1477.     {
  1478.         h_cursor := DllCall("CopyImage", "Ptr", visible ? handles.Default : handles.Blank, "UInt", 2, "Int", 0, "Int", 0, "UInt", 0)
  1479.         DllCall("SetSystemCursor", "Ptr", h_cursor, "UInt", id)
  1480.     }
  1481. }
  1482.  
  1483. class MenuItemInfo
  1484. {
  1485.     CbSize: u32 := ObjGetDataSize(this), FMask: u32, FType: u32, FState: u32, WID: u32, HSubMenu: iptr, HbmpChecked: iptr, HbmpUnchecked: iptr, DwItemData: uptr, DwTypeData: iptr
  1486.     Cch: u32, HbmpItem: iptr
  1487. }
  1488.  
  1489. class Point
  1490. {
  1491.     X: i32, Y: i32
  1492. }
  1493.  
  1494. /*
  1495. Example usage: (pointerDeviceEventHook := PointerDeviceHook("Move|LButton Down|LButton Up", HandlePointerDeviceEvent)).Start()
  1496.  
  1497. /** @param {PointerDeviceHook.EventInfo} eventInfo Pointer device event info */`
  1498. HandlePointerDeviceEvent(eventInfo)
  1499. {
  1500.     ToolTip(Format("
  1501.    (
  1502.        x{1}, y{2}
  1503.         EventAction : {3}
  1504.         EventKey    : {4}
  1505.         KeyUsageCount   : {5}
  1506.         KeyUsageTime    : {6}
  1507.         PressDuration   : {7}
  1508.         IsPenAction : {8}
  1509.    )", eventInfo.Pt.X, eventInfo.Pt.Y, eventInfo.Action, eventInfo.Key, eventInfo.KeyUsageCount, eventInfo.KeyUsageTime, eventInfo.KeyPressDuration, eventInfo.IsPenAction))
  1510. }
  1511. */
  1512. class PointerDeviceHook
  1513. {
  1514.     class InternalEventInfo
  1515.     {
  1516.         Pt: Point
  1517.         MouseData: i32 ; Necessary cast to `Int`
  1518.         Flags: u32
  1519.         Time: u32
  1520.         ExtraInfo: uptr
  1521.     }
  1522.  
  1523.     class EventInfo
  1524.     {
  1525.         Pt => this._IsPtAdaptive ? PointerDeviceHook.EventInfo.LatestPt : this._Pt
  1526.  
  1527.         /** @prop {string} Action The event action */
  1528.         Action => this._IsActionAdaptive ? (PointerDeviceHook.EventInfo.LatestAction ?? this._Action) : this._Action
  1529.  
  1530.         /** @prop {string} Key The event key */
  1531.         Key => PointerDeviceHook.EventInfo.IsKeyPressedDown ? PointerDeviceHook.EventInfo.RetainedKey : this._Key
  1532.  
  1533.         /** @prop {integer} KeyUsageCount Count how many times a key gets pressed in a short time (`KeyUsageCountTimeThreshold`) */
  1534.         KeyUsageCount => PointerDeviceHook.EventInfo.IsKeyPressedDown ? PointerDeviceHook.EventInfo.RetainedKeyUsageCount : this._KeyUsageCount
  1535.  
  1536.         /** @prop {string} KeyUsageTime The time when the event key was pressed, scrolled, or used for a pen action */
  1537.         KeyUsageTime => PointerDeviceHook.EventInfo.IsKeyPressedDown ? PointerDeviceHook.EventInfo.RetainedKeyUsageTime : this._KeyUsageTime
  1538.  
  1539.         /** @prop {integer} KeyPressDuration The time elapsed since this key was pressed */
  1540.         KeyPressDuration => (this.KeyUsageTime ? A_TickCount - this.KeyUsageTime : 0)
  1541.  
  1542.         /** @prop {integer} IsPenAction Whether or not the event is caused by a pen pointer device (not detected when using drawing tablet) */
  1543.         IsPenAction => PointerDeviceHook.EventInfo.IsKeyPressedDown ? PointerDeviceHook.EventInfo.RetainedIsPenAction : this._IsPenAction
  1544.  
  1545.         /** @prop {boolean} IsKeyPressedDown The hook does not repeatedly trigger the down event while a key is pressed down, so those `onEvent` callbacks use timer & keeps relevant info */
  1546.         static IsKeyPressedDown := false
  1547.  
  1548.         static __New() => this.LatestPt := Point()
  1549.         __New() => this._Pt := Point()
  1550.     }
  1551.  
  1552.     /** @prop {Map} MsgList A list of message codes and actions (the commented wheel actions can also be used in the `PointerDeviceHook` constructor) */
  1553.     MsgList := Map(
  1554.         512, "Move",
  1555.         513, "LButton Down",
  1556.         514, "LButton Up",
  1557.         516, "RButton Down",
  1558.         517, "RButton Up",
  1559.         519, "MButton Down",
  1560.         520, "MButton Up",
  1561.         523, "XButton{:d} Down",
  1562.         524, "XButton{:d} Up")
  1563.         ;โ€”โ€”, "WheelUp"
  1564.         ;โ€”โ€”, "WheelDown"
  1565.  
  1566.     /** @prop {integer} ProcHandle SetWindowsHookEx */
  1567.     ProcHandle := 0
  1568.  
  1569.     /** @prop {Map} PriorKeyObjects The map logs the time of when keys were previously pressed, as well as the count (both saved inside an object which is associated with a key) */
  1570.     PriorKeyObjects := Map()
  1571.  
  1572.     /** @prop {integer} KeyUsageCountTimeThreshold The time in which the usage of the event key gets counted, or reset when the time threshold is reached (milliseconds) */
  1573.     KeyUsageCountTimeThreshold := 500
  1574.  
  1575.     /**
  1576.      * @param {string} [action="All"] Move, LButton Down, MButton Up, etc (the `MsgList` property shows all of them)
  1577.      * @param {(hookObj) => Integer} onEvent This callback gets called on the event (to block mouse actions the callback must return true w/ default value `shouldMaintainResponsiveness`)
  1578.      * @param {integer} [shouldMaintainResponsiveness=false] Default is False, causing it to call `onEvent` in this thread in favor of mouse-action-blocking capability (consider using timer
  1579.      * in `onEvent`). Specify True to call it in a different thread if the `onEvent` code causes considerable mouse lag, as a result the Proc becomes incapable of blocking mouse actions
  1580.      * @param {integer} [criticalMode=0] Default is Disabled Mode. A (positive) Enabled Mode value is the message check interval. Specifying -1 turns on Critical but disables message checks
  1581.      */
  1582.     __New(action := "All", onEvent := (*) => 0, shouldMaintainResponsiveness := false, criticalMode := 0)
  1583.     {
  1584.         static WM_LBUTTONDOWN := 0x0201, WM_LBUTTONUP := 0x0202, WM_RBUTTONDOWN := 0x0204, WM_RBUTTONUP := 0x0205, WM_MBUTTONDOWN := 0x0207, WM_MBUTTONUP := 0x0208, WM_MOUSEWHEEL := 0x020A
  1585.             , WM_XBUTTONDOWN := 0x020B, WM_XBUTTONUP := 0x020C, LLMHF_INJECTED := 0x00000001, MI_WP_SIGNATURE := 0xFF515700, SIGNATURE_MASK := 0xFFFFFF00
  1586.  
  1587.         ; This callback gets executed when a pointer-device hook event occurs. The fast mode should be used only when it is known exactly which thread(s) this callback will be called from
  1588.         this.InternalCallback := CallbackCreate(PointerDeviceProc, (criticalMode && criticalMode != "Off") ? "F" : unset, 3)
  1589.  
  1590.         PointerDeviceProc(nCode, wParam, lParam)
  1591.         {
  1592.             if (criticalMode = -1 || criticalMode)
  1593.                 Critical(criticalMode)
  1594.  
  1595.             internalEventInfo := StructFromPtr(PointerDeviceHook.InternalEventInfo, lParam)
  1596.             eventInfo := PointerDeviceHook.EventInfo()
  1597.  
  1598.             ; `internalEventInfo.MouseData` contains a reserved low-order word, which we don't need, and the high-order word is the leftmost 16 bits (bitshift removes the rest).
  1599.             ; `PointerDeviceHook.EventInfo.IsKeyPressedDown` is mainly set at this point so that the up event will also stop the repeated down event timer when the up action isn't hooked
  1600.             switch (wParam)
  1601.             {
  1602.                 case WM_MOUSEWHEEL: eventInfo._Action := (internalEventInfo.MouseData >> 16) > 0 ? "WheelUp" : "WheelDown", PointerDeviceHook.EventInfo.IsKeyPressedDown := false
  1603.                 case WM_XBUTTONDOWN: eventInfo._Action := Format(this.MsgList[wParam], internalEventInfo.MouseData >> 16), PointerDeviceHook.EventInfo.IsKeyPressedDown := true
  1604.                 case WM_XBUTTONUP: eventInfo._Action := Format(this.MsgList[wParam], internalEventInfo.MouseData >> 16), PointerDeviceHook.EventInfo.IsKeyPressedDown := false
  1605.                 case WM_LBUTTONDOWN, WM_RBUTTONDOWN, WM_MBUTTONDOWN: eventInfo._Action := this.MsgList[wParam], PointerDeviceHook.EventInfo.IsKeyPressedDown := true
  1606.                 case WM_LBUTTONUP, WM_RBUTTONUP, WM_MBUTTONUP: eventInfo._Action := this.MsgList[wParam], PointerDeviceHook.EventInfo.IsKeyPressedDown := false
  1607.                 default: eventInfo._Action := this.MsgList.Has(wParam) ? this.MsgList[wParam] : 0
  1608.             }
  1609.  
  1610.             if (nCode < 0 || (action != "All" && !InStr(action, eventInfo._Action)))
  1611.                 return CallNextHookEx(nCode, wParam, lParam)
  1612.  
  1613.             eventInfo._IsPtAdaptive := eventInfo._IsActionAdaptive := false
  1614.             eventInfo._KeyUsageTime := eventInfo._KeyUsageCount := eventInfo._Key := 0
  1615.             eventInfo._Pt.X := internalEventInfo.Pt.X
  1616.             eventInfo._Pt.Y := internalEventInfo.Pt.Y
  1617.  
  1618.             if (eventInfo._Action && eventInfo._Action != "Move")
  1619.             {
  1620.                 if (!this.PriorKeyObjects.Has(eventInfo._Action))
  1621.                     this.PriorKeyObjects[eventInfo._Action] := {Time: internalEventInfo.Time, Count: 0}
  1622.  
  1623.                 priorKey := this.PriorKeyObjects[eventInfo._Action]
  1624.                 eventInfo._Key := eventInfo._Action
  1625.                 eventInfo._KeyUsageCount := priorKey.Count += internalEventInfo.Time - priorKey.Time < this.KeyUsageCountTimeThreshold ? 1 : -priorKey.Count + 1 ; Resets to 1 if false
  1626.                 eventInfo._KeyUsageTime := priorKey.Time := internalEventInfo.Time
  1627.                 eventInfo._IsPenAction := DetermineIsPenAction(internalEventInfo.ExtraInfo)
  1628.                
  1629.                 if (PointerDeviceHook.EventInfo.IsKeyPressedDown)
  1630.                 {
  1631.                     keyDownEventInfo := eventInfo.Clone()
  1632.                     keyDownEventInfo._IsPtAdaptive := keyDownEventInfo._IsActionAdaptive := true
  1633.                     PointerDeviceHook.EventInfo.LatestPt.X := eventInfo._Pt.X
  1634.                     PointerDeviceHook.EventInfo.LatestPt.Y := eventInfo._Pt.Y
  1635.                     PointerDeviceHook.EventInfo.LatestAction := unset
  1636.                     PointerDeviceHook.EventInfo.RetainedKey := eventInfo._Key
  1637.                     PointerDeviceHook.EventInfo.RetainedKeyUsageCount := eventInfo._KeyUsageCount
  1638.                     PointerDeviceHook.EventInfo.RetainedKeyUsageTime := internalEventInfo.Time
  1639.                     PointerDeviceHook.EventInfo.RetainedIsPenAction := eventInfo._IsPenAction
  1640.                     SetTimer(() => (this.ProcHandle && PointerDeviceHook.EventInfo.IsKeyPressedDown ? onEvent(keyDownEventInfo) : SetTimer(, 0)), 50)
  1641.                 }
  1642.             }
  1643.             else if (PointerDeviceHook.EventInfo.IsKeyPressedDown)
  1644.             {
  1645.                 PointerDeviceHook.EventInfo.LatestPt.X := eventInfo._Pt.X
  1646.                 PointerDeviceHook.EventInfo.LatestPt.Y := eventInfo._Pt.Y
  1647.                 PointerDeviceHook.EventInfo.LatestAction := eventInfo._Action
  1648.             }
  1649.             else
  1650.                 eventInfo._IsPenAction := DetermineIsPenAction(internalEventInfo.ExtraInfo)
  1651.  
  1652.             if (shouldMaintainResponsiveness)
  1653.             {
  1654.                 SetTimer(() => onEvent(eventInfo), -1)
  1655.  
  1656.                 return CallNextHookEx(nCode, wParam, lParam)
  1657.             }
  1658.             else
  1659.                 return onEvent(eventInfo) && !(internalEventInfo.Flags & LLMHF_INJECTED) ? true : CallNextHookEx(nCode, wParam, lParam)
  1660.         }
  1661.  
  1662.         DetermineIsPenAction(extraInfo) => ((extraInfo & SIGNATURE_MASK) = MI_WP_SIGNATURE)
  1663.         CallNextHookEx(nCode, wParam, lParam) => DllCall("CallNextHookEx", "Ptr", 0, "Int", nCode, "UPtr", wParam, "Ptr", lParam)
  1664.     }
  1665.  
  1666.     /** Warning: Take caution when blocking mouse actions, you should not call this inside a mouse hotkey prefixed w/ the (~) tilde symbol (to make `Stop` unblock mouse actions properly) */
  1667.     Start()
  1668.     {
  1669.         if (!this.ProcHandle)
  1670.             this.ProcHandle := DllCall("SetWindowsHookEx", "Int", WH_MOUSE_LL := 14, "Ptr", this.InternalCallback, "Ptr", GetModuleHandle(), "UInt", 0)
  1671.  
  1672.         GetModuleHandle() => DllCall("GetModuleHandle", "UInt", 0, "Ptr")
  1673.     }
  1674.    
  1675.     Stop()
  1676.     {
  1677.         if (this.ProcHandle && DllCall("UnhookWindowsHookEx", "Ptr", this.ProcHandle))
  1678.             this.ProcHandle := 0
  1679.     }
  1680.  
  1681.     __Delete() => (this.InternalCallback && (this.Stop(), CallbackFree(this.InternalCallback), this.InternalCallback := 0))
  1682. }
  1683.  
  1684. OpenGoogle(*)
  1685. {
  1686.     SystemCursor("Show")
  1687.  
  1688.     if (FileExist(A_ProgramFiles "\Google\Chrome\Application\chrome.exe"))
  1689.     {
  1690.         if (ProcessExist("chrome.exe") || !(hasTabsOutlinerExtension := DirExist(EnvGet("LocalAppData") "\Google\Chrome\User Data\Default\Extensions\eggkanocgddhmamlbiijnphhppkpkmkl")))
  1691.             Run("chrome.exe https://www.google.com/ --start-maximized --disable-features=GlobalMediaControls")
  1692.         else
  1693.         {
  1694.             HookEvent(EVENT_OBJECT_NAMECHANGE, HandleNameChangedTabsOutlinerEvent)
  1695.             Run("chrome.exe https://www.google.com/ --start-maximized --disable-features=GlobalMediaControls")
  1696.         }
  1697.     }
  1698.     else
  1699.         Run("https://www.google.com/")
  1700. }
  1701.  
  1702. HandleNameChangedTabsOutlinerEvent(hWinEventHook, event, hWnd, *)
  1703. {
  1704.     static isBeingClosed := false
  1705.  
  1706.     try
  1707.         if (WinGetTitle(hWnd) = "_crx_eggkanocgddhmamlbiijnphhppkpkmkl" && !isBeingClosed)
  1708.         {
  1709.             isBeingClosed := true
  1710.             try WinSetTransparent(0, hWnd) ; Gets rid of the close animation
  1711.             try WinClose(hWnd)
  1712.             DllCall("UnhookWinEvent", "Ptr", hWinEventHook)
  1713.             Sleep(-1) ; Discards queued events that might remain
  1714.             isBeingClosed := false
  1715.         }
  1716. }
  1717.  
  1718. OpenMaps(*)
  1719. {
  1720.     SystemCursor("Show")
  1721.     Run("shell:AppsFolder\Microsoft.WindowsMaps_8wekyb3d8bbwe!app")
  1722.  
  1723.     if (!WinWaitActive("Maps ahk_class ApplicationFrameWindow",, 3))
  1724.         return
  1725.  
  1726.     Sleep(300)
  1727.     Send("^y{Ctrl down}")
  1728.    
  1729.     loop (50)
  1730.         Sleep(50), Send("{Home}")
  1731.  
  1732.     Send("{Ctrl up}")
  1733. }
  1734.  
  1735. MouseIsOver(winTitle, winText?, excludeTitle?, excludeText?) => (MouseGetPos(,, &winId), WinExist(winTitle " ahk_id " winId, winText?, excludeTitle?, excludeText?))
  1736.  
  1737. HookEvent(event, fnObj, pid := 0) => DllCall("SetWinEventHook", "UInt", event, "UInt", event, "Ptr", 0, "Ptr", CallbackCreate(fnObj), "UInt", pid, "UInt", 0, "UInt", 0)
  1738.  
  1739. /* EXAMPLE
  1740. [_ActiveContextWindows]
  1741. ahk_exe Taskmgr.exe=services.msc
  1742. [_ExistingContextWindows]
  1743. [_ExistingContextWindowPriority1]
  1744. VOXEL WAR ahk_exe Unity.exe=shell:Profile\Documents\Unity projects\VOXEL WAR\Assets
  1745. [_ExistingContextWindowPriority2]
  1746. VOXEL WAR ahk_exe devenv.exe=shell:Profile\Documents\Unity projects\VOXEL WAR\Assets\Scripts
  1747. [_ExistingContextWindowPriority3]
  1748. ahk_exe Unity.exe=shell:Profile\Documents\Unity projects
  1749. [_ExistingContextWindowPriority4]
  1750. ahk_exe devenv.exe=shell:Profile\Documents\Unity projects
  1751. [_ExistingContextWindowPriority5]
  1752. ahk_exe notepad.exe=chrome.exe https://www.autohotkey.com/docs/alpha/ChangeLog.htm --start-maximized --disable-features=GlobalMediaControls
  1753. [_ExistingContextWindowPriority6]
  1754. Workspace - Visual Studio Code ahk_exe chrome.exe=chrome.exe https://www.autohotkey.com/docs/alpha/ChangeLog.htm --start-maximized --disable-features=GlobalMediaControls
  1755. [_PreferredSmartRunInput]
  1756. %LocalAppData%
  1757. [_AspectRatioVideosContextFolders]
  1758. C:/Users/loren/Downloads/Films
  1759. C:/Users/loren/AppData/Local/Temp/Popcorn Time
  1760. X:/
  1761. D:/Films
  1762. E:/Opslag
  1763. [_FullscreenWindowsUnhideTaskbar]
  1764. Sourcetree ahk_exe SourceTree.exe
  1765. Software Ideas Modeler  ahk_exe SoftwareIdeasModeler.exe
  1766. Popcorn-Time ahk_exe Popcorn-Time.exe
  1767. Epic Games Launcher ahk_exe EpicGamesLauncher.exe
  1768. GeForce Experience ahk_exe NVIDIA GeForce Experience.exe
  1769. */
  1770.  
  1771. /* Edit these variables yourself if necessary (e.g. to make it more specific you can add the ahk_class, and for the opposite effect you can replace the ahk_exe with an ahk_class or title)
  1772. [ActiveContextWindows]
  1773. [ExistingContextWindows]
  1774. [PreferredSmartRunInput]
  1775. [AspectRatioVideosContextFolders]
  1776. [FullscreenWindowsUnhideTaskbar]
  1777. */
  1778.  
Comments
  • Lorenzo501
    66 days
    # text 1.28 KB | 0 0
    1. [TEST ALL THIS GODMODE STUFF AGAIN IF I'M STILL GONNA USE IT, MIGHT ALL BE RESOLVED NOW THAT I HAVE CHANGED SOME STUFF]
    2. using godmode works but using double-press/long-press/triple-press to set something doesn't seem to load the new hotkey that has been added to the INI, only when I restart the script
    3. - tested with both [active] & [existing], they both have the issue
    4. also godmode overwrites the [active] if one of the context wnd entry exists already but with [existing] it just adds it below instead of overwriting, not sure if that's rly a problem tho
    5. keeping godmode hotkey pressed down for twice as long repeats its function twice, so it opens two INI save windows, consistently with the active context wnd only ([existing] is mostly fine)
    6. - but letting go after the normal time and then pressing it down again, that won't open a second INI save window.. can't even use the quick-press with an INI save wnd open (strange)
    7. keeping godmode hotkey pressed down for the normal time opens one INI save window and also triggers a quick-press to open a destination of the active context wnd only ([existing] is fine)
    8. - but letting go after the normal time and then a quick-press triggers [existing], not [active], and doing a long-press instead of quick-press now 'suddenly' does open a 2nd save window o.o
  • Lorenzo501
    37 days
    # text 0.15 KB | 0 0
    1. this has code to fix the recycle bin, it randomly resets which columns are shown and the sorting:
    2. https://www.autohotkey.com/boards/viewtopic.php?f=6&t=33129
  • Lorenzo501
    35 days
    # text 0.60 KB | 0 0
    1. bit offtopic but w/e, "Context Menu New AutoHotkey Script.reg":
    2. Windows Registry Editor Version 5.00
    3.  
    4. ; I removed it, so this will add it back
    5. [HKEY_CLASSES_ROOT\.ahk\ShellNew]
    6. "Command"="\"C:\\Program Files\\AutoHotkey\\UX\\AutoHotkeyUX.exe\" \"C:\\Program Files\\AutoHotkey\\UX\\ui-newscript.ahk\" \"%1\""
    7.  
    8. ; I copied the template from %ProgramFiles%\AutoHotkey\UX\Templates to %SystemRoot%\ShellNew, took out the "v" of "v2.0" inside the script, removed the multi-line comment and renamed it.
    9. ; So this will remove the value "FileName"="CustomTemplate.ahk"
    10. [HKEY_CLASSES_ROOT\.ahk\ShellNew]
    11. "FileName"=-
  • Lorenzo501
    15 days
    1. ; These are merely so that they get buffered if the OS were to lag, which might cause the `SetVlcVideoOutputForRelevantFeatureFix` fn to be taking too long to finish (then VLC opens without the setting change, although I highly doubt that this will ever happen.. my tests revealed that the fn finishes before the `LButton up` after selection)
    2. #HotIf (WinActive("ahk_group FileExplorer"))
    3. LButton::Send("{LButton down}"), KeyWait("LButton"), Send("{LButton up}")
    4. Enter::Send("{Enter}"), KeyWait("Enter")
    5.  
    6. GroupAdd("FileExplorer", "ahk_class Progman")
    7. GroupAdd("FileExplorer", "ahk_class WorkerW")
    8. GroupAdd("FileExplorer", "ahk_class CabinetWClass")
    9. GroupAdd("FileExplorer", "ahk_class ExploreWClass")
  • Lorenzo501
    2 days
    # text 0.28 KB | 0 0
    1. the following can be used instead of ControlSend("{Enter}") in the XButton* hotkeys of the latest Time Saver version, but I decided not to use it (it's the only way to close the menu properly, b/c using WinClose/WinHide too fast makes it impossible to create menus): ControlSend("{Esc}")
  • Lorenzo501
    1 day
    1. ; this has not been tested, but might work (I'm trying an even better way for now, activating WorkerW and then GroupActivate to go back)
    2.  
    3. #HotIf (WinActive("ahk_exe notepad.exe") || WinActive("- Visual Studio Code ahk_class Chrome_WidgetWin_1"))
    4. ;MButton::WinActivate("ahk_class Progman")
    5. MButton::
    6. {
    7.     A_ControlDelay := -1 ; Changes only the control delay of the thread made for this specific hotkey
    8.     global lastActiveWnd := WinExist("A")
    9.     WinActivate("ahk_class Progman")
    10.     ControlClick("x0 y0", "ahk_class Progman",,,, "Pos")
    11.     HookEvent(EVENT_SYSTEM_FOREGROUND, HandleActivatedWindowTextEditorEvent)
    12.  
    13.     HandleActivatedWindowTextEditorEvent(hWinEventHook, event, hWnd, *)
    14.     {
    15.         try
    16.             if (!WinGetClass(hWnd) = "Progman" || !WinGetClass(hWnd) = "WorkerW")
    17.             {
    18.                 DllCall("UnhookWinEvent", "Ptr", hWinEventHook)
    19.                 global lastActiveWnd := unset
    20.             }
    21.     }
    22. }
    23.  
    24. ;#HotIf (WinActive("ahk_class WorkerW"))
    25. #HotIf (WinActive("ahk_class Progman"))
    26. MButton::try WinActivate(lastActiveWnd)
Add Comment
Please, Sign In to add comment