Wrong Exit Reason Displayed on Script Reload

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
1100++
Posts: 78
Joined: 10 Feb 2018, 19:05

Wrong Exit Reason Displayed on Script Reload

16 Jan 2020, 07:24

Whenever I reload this particular script, it always gives "Exit" as the exit reason, instead of "Reload".

Code: Select all

; // Directives //
#NoEnv
#LTrim
#UseHook
#SingleInstance
#KeyHistory 500
#Include %A_ScriptDir%
#Hotstring EndChars -%()[]{}:'/\,.?! `n`t;"	;"

; // Auto-Execute Section //
SetBatchLines -1
SetWorkingDir %A_ScriptDir%

FileEncoding UTF-8
SendMode Input
SetWinDelay 0
SetControlDelay -1
SetTitleMatchMode 2
SetFormat FloatFast, 0.16

Menu Tray, Tip, % SubStr(A_ScriptName, 1, InStr(A_ScriptName, ".", true, 0) - 1) " (PID: " (ScriptPID := DllCall("GetCurrentProcessId", "uInt")) ")"

; / Environment Variables /
DllCall("QueryPerformanceFrequency", "Int64*", freq), hPowrProf := DllCall("LoadLibrary", "Str", "PowrProf", "Ptr")
EnvGet SysDrive, SYSTEMDRIVE
EnvGet UserProfile, USERPROFILE
EnvGet LocalAppData, LOCALAPPDATA
EnvGet AllUsersProfile, ALLUSERSPROFILE
EnvGet PrgFiles, PROGRAMFILES

; / Script Variables /
MainScriptIni := "..\Main Script.ini", System32 := A_WinDir "\System32", UserLib := (AhkDir := A_MyDocuments "\AutoHotkey") "\Lib"
, AltDataP := "--user-data-dir=""" LocalAppData "\Google\Chrome\User Data\Alternate""", FlashPlayer := ProgramFiles "\Adobe\Flash Player\11.7.700.202\flashplayer_11_sa.exe"
, OldDownloads := (FlashDrive := A_MyDocuments "\Flash Drive") "\(1) Personal\Downloads", DesktopCLSID := "쵶ᔧ俽ށ씙ڼ", DesktopModeCLSID := "诗렽뙎䩠涙磯Ễޠ"
, EnergyStarCLSID := "櫓샪慅䑇庡륟颛", HighPerformanceCLSID := "翚豞䪖薚谺屣", VarSetCapacity(AHKNotesSep, 361), StrPut(CharMulti(8212, 120), &AHKNotesSep, "UTF-8")

; / Main Script.ini /
IniWrite % ScriptPID, %MainScriptIni%, Settings, PID
;Gosub InitWindowCache
IniRead SaveString, %MainScriptIni%, Settings, SaveString, %A_Space%
IniRead KillExtDlg, %MainScriptIni%, Settings, KillExtDlg, 0
IniRead DisableScreensaver, %MainScriptIni%, Settings, DisableScreensaver, % -1
Commands := IniReadUnescape(MainScriptIni, "Lists", "Commands")
RunList := IniReadUnescape(MainScriptIni, "Lists", "RunList")
IniRead LastFunction, %MainScriptIni%, Settings, LastFunction, %A_Space%
IniRead aDir, %MainScriptIni%, Settings, aDir, %A_Space%
IniRead LastScriptHwnd, %MainScriptIni%, Settings, LastHwnd, %A_Space%
IniWrite %A_ScriptHwnd%, %MainScriptIni%, Settings, ScriptHwnd
IniRead LogDir, %MainScriptIni%, Settings, LogDir, %A_Space%
IniRead Date, %MainScriptIni%, Settings, Date, %A_Space%
If (A_Today := Now("yyyy.MM.dd")) = Date {
	IniRead Script#, %MainScriptIni%, Settings, Script#, 0
	IniWrite % ++Script#, %MainScriptIni%, Settings, Script#
} else {
	IniWrite % Script# := 1, %MainScriptIni%, Settings, Script#
	IniWrite % A_Today, %MainScriptIni%, Settings, Date
}

Menu Tray, Add
Menu Tray, Add, Execute Command, InputCommand

; / Window, Process, & Message Procedures /
;DllCall("SetProcessShutdownParameters", "uInt", 0x4FF, "uInt", 0), OnMessage(0x11, "CheckShutdown")	;, OnMessage(0x404, "AHK_NOTIFYICON")

; / Disable Sceensaver /
Switch DisableScreensaver {
	case 0:
		ReasonString := "User Desktop Mode Active"
		Menu PowerSettings, Add, User Desktop Mode Active, DesktopLabel, +Radio
		Menu PowerSettings, Add, Enter System Desktop Mode, ToggleDesktopMode
		Menu PowerSettings, Check, System Desktop Mode Active
	case 1:
		ReasonString := "System Desktop Mode Active"
		Menu PowerSettings, Add, Enter User Desktop Mode, ToggleDesktopMode
		Menu PowerSettings, Add, System Desktop Mode Active, DesktopLabel, +Radio
		Menu PowerSettings, Check, System Desktop Mode Active
	case -1: 
		Menu PowerSettings, Add, Enter User Desktop Mode, ToggleDesktopMode
		Menu PowerSettings, Add, Enter System Desktop Mode, ToggleDesktopMode
		Goto DontDisableScreensaver
} VarSetCapacity(ReasonContext, A_PtrSize + 8), NumPut(1, ReasonContext, 4, "uInt")
, NumPut(&ReasonString, ReasonContext, 8, "Ptr"), PowerRequestObject := DllCall("PowerCreateRequest", "Str", ReasonContext, "Ptr")
, DllCall("PowerSetRequest", "Ptr", PowerRequestObject, "Int", 0)
Menu PowerSettings, Add, Exit Desktop Mode, ToggleDesktopMode



DontDisableScreensaver:

Menu Tray, Add, Power Settings, :PowerSettings


; / Window Groups /

GroupCreate("Explorer", "ahk_class CabinetWClass", "ahk_class ExploreWClass", "Save As ahk_class #32770")
, GroupCreate("ExplorerUI", "ahk_class Shell_TrayWnd", "ahk_class WorkerW", "ahk_class DV2ControlHost", "ahk_class NotifyIconOverflowWindowr")
, GroupCreate("Emulator", "ahk_class EPSX", "ahk_class SDL_app", "ahk_class RetroArch")

;Gosub AppShortcutInit
;Gosub InitScriptEdit
;Gosub WindowPropertiesInit
;Gosub Test
OnExit("ConfirmReload")
OnExit("ExitMsg")
OnExit ExitSub
SetTimer PsxDisableScreensaver, -0
Loop {
	KeyWait RWin, D
	DllCall("QueryPerformanceCounter", "Int64*", RWinP)
	KeyWait RWin
} return

PsxDisableScreensaver:
VarSetCapacity(ReasonContext, A_PtrSize + 8), NumPut(1, ReasonContext, 4, "uInt")
Loop {
	WinWaitActive ahk_group Emulator
	WinGetClass EmulatorClass
	Switch EmulatorClass {
		case "EPSX": ReasonString := "An ePSXe emulation window is currently active."
		case "SDL_app": ReasonString := "Mednafen is currently active."
		case "RetroArch": ReasonString := "RetroArch is currently active."
	} NumPut(&ReasonString, ReasonContext, 8, "Ptr")
	, PowerRequestObject := DllCall("PowerCreateRequest", "Str", ReasonContext, "Ptr")
	, DllCall("PowerSetRequest", "Ptr", PowerRequestObject, "Int", 0)
	WinWaitNotActive ahk_group Emulator
	DllCall("PowerClearRequest", "Ptr", PowerRequestObject, "Int", 0), DllCall("CloseHandle", "Ptr", PowerRequestObject)
} return

ConfirmReload(ExitReason, ExitCode) {
	MsgBox % ExitReason
	If (ExitReason == "Reload")
		MsgBox 4, Confirm Reload, Are you sure you want to reload the script?
	IfMsgBox No
		return true
	return false
}

ExitMsg(ExitReason, ExitCode) {
	If (ExitReason == "Reload")
		MsgBox The script is reloading.
	return false
}

; // Global Hotkeys //

#+a:: RunApp(ProgramFiles "\Audacity\audacity.exe",, "max")
#^a:: Open("appwiz.cpl")
#!a:: Open(A_AppData)
#+b:: Open(UserProfile "\BitTorrent")
#^+b:: Open(aDir)
#c:: RunApp(ComSpec, System32)
#+c:: RunAppAdmin(ComSpec, System32)
#!c:: RunActivate("charmap.exe")
<#+d:: Open(A_MyDocuments)
#^d:: Open("control color")
#!d:: Open(UserProfile "\Downloads")
#^+d:: Open("D:")
#!+d:: Open(A_MyDocuments "\Downloads (003student)")
#+e:: Open("::{20D04FE0-3AEA-1069-A2D8-08002B30309D}")
#f:: RunApp("freecell.exe")
#+f:: RunApp("firefox.exe")
#^f:: Open("control folders")
#!f:: RunApp(FlashPlayer)
#^+f:: Open(FF_Main)
#!+f:: Open(FlashDrive)
#+g:: RunApp("chrome.exe " AltDataP)
#^g:: RunApp(A_WinDir "\GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}")
#!g:: Open(LocalAppData "\Google\Chrome\User Data\Default")
#h:: (HelpWin := DllCall("FindWindow", "Str", "HH Parent", "Str", "AutoHotkey Help")) ? (DllCall("IsWindowVisible", "uPtr", HelpWin)
	or DllCall("ShowWindowAsync", "uPtr", HelpWin, "Int", 5), DllCall("SwitchToThisWindow", "uPtr", HelpWin)) : RunApp("hh.exe """ ProgramFiles "\AutoHotkey\AutoHotkey.chm""")
#^h:: RunHelp("AutoHotkey Help", ProgramFiles "\AutoHotkey\AutoHotkey.chm")
#+h:: Open(A_MyDocuments "\AutoHotkey")
#!h:: OpenNotepad("Untitled.ahk", A_ScriptDir)
#^i:: Open("control inetcpl")
#!i:: RunApp("msinfo32.exe")
#k:: RunActivate("calc.exe")
#+k:: RunActivate("PowerCalc.exe")
#^k:: Open("control keyboard")
#!k:: RunActivate(ProgramFiles "\KeyTweak\KeyTweak.exe")
#+l:: Open(UserLib)
#^l:: Open("control international")
#^+l:: Open(AhkDir "\Logs")
#+m:: Open(A_ScriptDir)
#^m:: Open("control mouse")
#!m:: RunApp(A_MyDocuments "\Mednafen\mednaffe.exe")	; RunApp("winmine.exe")
#^!m:: RunApp("msconfig.exe")
#n:: OpenNotepad()
#+n:: RunApp("notepad++.exe")
#!n:: RunApp("notepad++.exe -multiInst -nosession -notabbar")
#p:: RunApp("mspaint.exe")
#+p:: Open(UserProfile "\Pictures")
#^p:: Open("control /name Microsoft.Personalization")
#^+p:: Open("control /name Microsoft.PowerOptions")
#!p:: Run cmd /c start /high %UserProfile%\Downloads\ePSXe\ePSXe.exe -slowboot, %UserProfile%\Downloads\ePSXe, hide	; Open(UserProfile "\Downloads\Pictures")
#!+p:: Open(ProgramFiles)
#+r:: RunApp("ResourceHacker")
#+s:: Open(System32)
#^s:: Open("mmsys.cpl")
#!s:: Open("shell:sendto")
#!+s:: Open(A_Startup)
>#s:: RunApp("sol.exe")
#t:: RunApp("taskmgr.exe")
<#+t:: RunApp(LocalAppData "\Tor Browser\Start Tor Browser.lnk", LocalAppData "\Tor Browser")
#^t:: Open("cttune.cpl")
#^+t:: RunApp(System32 "\taskschd.msc /s")
#+u:: Open(UserProfile)
#^u:: Open("control /name Microsoft.UserAccounts")
#^+u:: Open(AllUsersProfile)
#!+u:: Open(SysDrive "\Users")
#w:: RunApp("wordpad.exe")
#+w:: RunApp("WINWORD.EXE",, "max")
#x:: RunApp("SnippingTool.exe")
#+x:: RunApp("EXCEL.EXE")
#y:: Open("::{645FF040-5081-101B-9F08-00AA002F954E}")
#+y:: Open(AltProfile "\My Documents\YGO")
#!y:: OpenWith(AltProfile "\My Documents\YGO\Deck Changes.xlsx", "EXCEL.EXE",, "max")
<#Home:: RunActivate("firefox.exe",, "max")
#!Home:: RunActivate("firefox.exe -P")
#F8:: RunApp("control.exe")
#F12:: RunApp("regedit")
#SC052:: Open(OldDownloads)
#SC04F:: Open(OldDownloads "\Downloads (1)")
#SC050:: Open(OldDownloads "\Downloads (2)")


; / URLs /

>#+a:: (AppURL := CopySel()) <> "" or InputGui(AppURL, "App Browse", "Enter the URL you want to browse to.", AppURL, 16) ? ChromeApp(AppURL)
>#+b:: ChromeApp("https://btc-e.com")
>#+d:: ChromeApp("bhdheahnajobgndecdbggfmcojekgdko", true)
>#+f:: ChromeApp("boeajhmfdjldchidhphikilcgdacljfm")
#g:: (GmailWin := WinExist(" - Gmail ahk_class Chrome_WidgetWin_1")) ? DllCall("SwitchToThisWindow", "Ptr", GmailWin) : ChromeApp("pjkljhegncpnkpknbcohdijeoejaedia")
>#+g:: (Query := CopySel()) <> "" or InputGui(Query, "Google Search",, Query, 16) ? ChromeApp("https://www.google.com/search?q=" Query)
	: ChromeApp("coobgpohoikkiipiblmjeljniedjpjpf")	; Run Google Search app
>#+h:: (QueryAHK := CopySel()) <> "" or InputGui(QueryAHK, "Search AutoHotkey.com",, QueryAHK, 16)
	? ChromeApp("http://www.google.com/cse?cx=008894931886257774458:qsymwz_o1tq&q=" QueryAHK)
>#+t:: ChromeApp("https://translate.google.com/" ((TransText := CopySel()) == "" ? "" : "#auto/en/" TransText))
>#+y:: InputBox(YugiohCardName, "Yu-Gi-Oh! Wikia Card Look-up", "Please enter the name of the card you want to look up (case sensitive).", CopySel())
	and (HttpQuery(YugiohPage := "http://yugioh.wikia.com/wiki/" StrReplace(StrTitle(YugiohCardName), " ", "_")) // 100 = 2 ? Open(YugiohPage)
	: Msg("The page you requested does not exist."))



; // Application Shortcuts //

;#Include Application Shortcuts.ahk



; // Hotrtrings //
#Hotstring c

; / Abreviations /
::w/o::without
::b/t::between
::m/b::maybe
:*r:<ascii>::ABCDEFGHIJKLMNOPQRSTUVWXYZ`nabcdefghijklmnopqrstuvwxyz`n0123456789`n!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ;"
::\adir::
SendRaw %aDir%%A_EndChar%
return


; / Character Input /
#Hotstring * ?
::\xp::XÞ
::\>=::≥
::\<=::≤
;::=/::≠
::\...::…
::\intg::∫
::\smileb::☻
::\smilew::☺
#Hotstring *0 ?0



; // AutoHotkey Auto-Replace //
;#Include Script Editing.ahk



; // Exit Subroutine //
ExitSub:
DllCall("PowerClearRequest", "Ptr", PowerRequestObject, "Int", 0)
If (DisableScreensaver <> -1)
	IniWrite % DisableScreensaver, %MainScriptIni%, Settings, DisableScreensaver
IniWrite % Hex(A_ScriptHwnd), %MainScriptIni%, Settings, LastHwnd
If (LastFunction <> "")
	IniWrite %LastFunction%, %MainScriptIni%, Settings, LastFunction
If (LastScript <> "")
	IniWrite %LastScript%, %MainScriptIni%, Settings, LastScript
ExitApp
MsgBox 0x40010, Error: Exit Failed, The script failed to terminate.`n`nExit Reason: %A_ExitReason%
return



; // Abort Shutdown //
/*
CheckShutdown(wParam, lParam) {
	return (!CacheUpdate() or YesNo("You still have windows cached.`n`nDo you still want to " (lParam & 0x80000000 ? "log off" : "shut down") "?"
		, "Continue " (lParam & 0x80000000 ? "Logff" : "Shutdown") "?", true) or IsWindowsVistaOrGreater()
		and !DllCall("ShutdownBlockReasonCreate", "Ptr", A_ScriptHwnd, "Str", "You have windows cached."))
		and (true, DllCall("SetProcessShutdownParameters", "uInt", 0x100, "uInt", 0))
}
*/

; / Abort Shutdown Override /
#IfWinActive ahk_class BlockedShutdownResolver
AppsKey::
	DllCall("ShutdownBlockReasonDestroy", "Ptr", A_ScriptHwnd)
	ExitApp
return
#If



#a:: MsgBox % (A_IsAdmin ? "Admin" : "Normal") "`n`nStarted: " GetProcessStartTime(ScriptPID, "dddd, MMMM d, yyyy @ h:mm:ss.nnn tt")


; // Script Actions //

; / Reload Script /

#F5:: Reload()
>#Enter:: Reload()


; / Main Script Window /

>#a:: ListLines
>#h:: ListHotkeys
>#k:: KeyHistory
>#v:: ListVars


; / Suspend Hotkeys /

<+SC045:: Suspend


; / Edit Main Script /
#F4:: OpenWith(A_ScriptDir, "notepad++")



; // Key & Shortcut Substitutions //

#IfWinNotActive ahk_class wxWindowNR

SC045:: Send ^c		; SC045 = Pause
+SC045:: Send ^x
#If !(InsDown or WinActive("ahk_class wxWindowNR"))
Ins:: Send ^v
+Ins::
Send {Ins down}
InsDown := true
return
#If InsDown
*Ins up::
	InsDown := false
	Send {Ins up}
return

#If !PageUpDown
>!Home::
Send {PgUp down}
PageUpDown := true
return
#If PageUpDown
~*Home::
Send {PgUp up}
PageUpDown := false
return
#If !PageDnDown
>!End::
Send {PgDn down}
PageDnDown := true
return
#If PageDnDown
~*End::
Send {PgDn up}
PageDnDown := false
return
#If



#m:: SoundSet -1, Master, Mute



ParseArrayKeys(Field) {
	Keys := [], QMode := Offset := 0
	Loop Parse, Field, `,"	; "
	{	If (Delim := SubStr(Field, Offset += StrLen(A_LoopField) + 1, 1)) == """" {
			If (QMode or LDelim == """" and A_LoopField <> "")
				Key .= A_LoopField
			else if (LDelim == ",")
				Key .= LTrim(A_LoopField)
			else Key .= """"
			QMode := !QMode
		} else if QMode
				Key .= A_LoopField ","
			else if (LDelim == ",")
				Keys.Push(Trim(A_LoopField))
			else Keys.Push(Key RTrim(A_LoopField)), Key := ""
		LDelim := Delim
	} return Keys
}


; // Adjust Mouse Speed //
#!+m:: DllCall("SystemParametersInfo", "uInt", 0x70, "uInt", 0, "uInt*", OrigMouseSpeed, "uInt", 0)
	, InputGui(NewMouseSpeed, "New Mouse Speed", "The current mouse speed is " OrigMouseSpeed ".  Type the desired mouse speed below.", OrigMouseSpeed, 16)
	and NewMouseSpeed > 0 and DllCall("SystemParametersInfo", "uInt", 0x71, "uInt", 0, "Int", NewMouseSpeed, "uInt", 0)


; // Insert Start Date/Time //

:*:~stdt;::
::\stdt::
	SendRaw % GetAppStartTime(DllCall("GetForegroundWindow", "uPtr"), "M/d/yyyy")
return
:*:~sstdt;::
	SendRaw % GetAppStartTime(DllCall("GetForegroundWindow", "uPtr"), "M-d-yyyy")
:*:~sttm;::
::\sttm::
	SendRaw % GetAppStartTime(DllCall("GetForegroundWindow", "uPtr"), "h꞉mm꞉ss tt")
return
:*:~stdtm;::
::\stdtm::
	SendRaw % GetAppStartTime(DllCall("GetForegroundWindow", "uPtr"), "M/d/yyyy h꞉mm꞉ss tt")
return
:*:~sstdtm;::
::\sstdtm::
	SendRaw % GetAppStartTime(DllCall("GetForegroundWindow", "uPtr"), "M-d-yyyy h꞉mm꞉ss tt")
return


; // Insert Current Date/Time //
:*:\now::
	SendRaw % GetLocalTime("M/d/yyyy h꞉mm꞉ss tt")
return
:*:\snow::
	SendRaw % GetLocalTime("M-d-yyyy h꞉mm꞉ss tt")
return



; / AutoHotkey Editing /

#IfWinActive Untitled - Notepad ahk_class Notepad
!+h:: WinSetTitle Untitled.ahk - Notepad
#IfWinActive Untitled.ahk - Notepad ahk_class Notepad
!+h:: WinSetTitle Untitled - Notepad
#If



; / Text Input /

<!/:: Send ÷
>!5:: Send √
<!+8:: Send •
>!a:: Send α
>!b:: Send β
>!d:: Send ∆
<!d:: Send δ
>!f:: Send φ
>!l:: Send ℓ
<!m:: Send µ
<!p:: Send π
>!q:: Send θ
<!Space:: Send  

>!Tab:: Send {U+9}
;<!':: Send ’
<!+':: Send “
>!+':: Send ”
>!-:: Send —
>!^-:: Send —
<!-:: Send –
<!+-:: Send −


; / Delimiter Insertion /

>!.:: SelAffix(" ", " ")
>!9:: SelAffixAdd("(", ")")
>!0:: SelAffix("(", ")")
>![:: SelAffix("[", "]")
>!]:: SelAffix("{", "}")
;<!9:: Send (){Left}
<![:: Send {{}{}}{Left}
>!':: SelAffix("""", """")



; // Insert Date //

#IfWinActive ahk_group Explorer

:*:\today::
Send % Now("M-d-yyyy")
return
^d:: Send % Now("yyyy-MM-dd (tt.hh.mm.ss)")
#If

:*:\today::
Send % Now("M/d/yyyy")
return

; // Get String Length //

<!+l:: MsgBox % (DllCall("GetWindowLong", "uInt", DllCall("GetForegroundWindow"), "Int", -20) & 8) << 15, Selection Length, % (SelString := CopySel()) <> ""
	? "Length:  " StrLen(SelString) "`n`n" SelString : "No string copied."


; // Get Word Count //

<!^+l:: MsgBox % (DllCall("GetWindowLong", "uInt", DllCall("GetForegroundWindow"), "Int", -20) & 8) << 15, Word Count, % (WordCountString := CopySel()) <> ""
	? "Word Count:  " (WordCount, RegExReplace(WordCountString, "\S+",, WordCount)) "`n`n" WordCountString : "No selection copied."


; // Get Char //

>!+a::
(CharString := CopySel()) <> "" ? (DllCall("QueryPerformanceCounter", "Int64*", P), CharCodes := CharCodes(CharString), DllCall("QueryPerformanceCounter", "Int64*", Q)
	, MessageStr := CharString "`n`n" CharCodes "`n`nTime: " SciNot((Q - P) / freq, 6) " sec") : MessageStr := "No characters copied."
MsgBox % (DllCall("GetWindowLong", "uInt", DllCall("GetForegroundWindow"), "Int", -20) & 8) << 15, Selection Chars, % MessageStr
return


; // Get # Lines //

<!+n:: MsgBox % (DllCall("GetWindowLong", "uInt", DllCall("GetForegroundWindow"), "Int", -20) & 8) << 15, Selection Linefeeds, % (LineString := CopySel()) <> ""
	? (Linefeeds, StrReplace(LineString, "`n", "`n", Linefeeds)) " linefeed" (Linefeeds == 1 ? "" : "s") " counted." : "No characters copied."


CharCodes(CharString) {
	CodeList := []
	Loop Parse, CharString
		LowCode > 0 ? LowCode := 0 : CodeList.Push(A_LoopField > "퟿" and A_LoopField < "�" and 0xDC00 <= (LowCode := NumGet(CharString, A_Index << 1, "uShort"))
			and LowCode < 0xE000 ? Ord(A_LoopField) - 0xD7C0 << 10 | LowCode - 0xD800 : Ord(A_LoopField))
   return Format(FastStrRepeat("{:02X} ", CodeList.Length() - 1) "{:02X}", CodeList*)
}



; // Windows Hotkeys //

#F3:: Send #f	; Windows file search
<#-:: Send #m	; Minimize all windows
#_:: Send #+m	; Unminimize windows



; // Application Volume //

>#SC053:: DllCall("GetWindowThreadProcessId", "Ptr", DllCall("GetForegroundWindow", "Ptr"), "uInt*", VolumePID), VolumeObject := GetVolumeObject(VolumePID)
	, VA_ISimpleAudioVolume_GetMute(VolumeObject, AppMute), VA_ISimpleAudioVolume_SetMute(VolumeObject, !AppMute), ObjRelease(VolumeObject)
>#NumpadAdd:: DllCall("GetWindowThreadProcessId", "Ptr", DllCall("GetForegroundWindow", "Ptr"), "uInt*", VolumePID), VolumeObject := GetVolumeObject(VolumePID)
	, VA_ISimpleAudioVolume_GetMasterVolume(VolumeObject, SoundLevel), VA_ISimpleAudioVolume_SetMasterVolume(VolumeObject, SoundLevel + 0.05), ObjRelease(VolumeObject)
>#NumpadSub:: DllCall("GetWindowThreadProcessId", "Ptr", DllCall("GetForegroundWindow", "Ptr"), "uInt*", VolumePID), VolumeObject := GetVolumeObject(VolumePID)
	, VA_ISimpleAudioVolume_GetMasterVolume(VolumeObject, SoundLevel), VA_ISimpleAudioVolume_SetMasterVolume(VolumeObject, SoundLevel - 0.05), ObjRelease(VolumeObject)



; // Focus Taskbar //

#b:: DllCall("SwitchToThisWindow", "Ptr", DllCall("FindWindow", "Str", "Shell_TrayWnd", "Ptr", 0))



; // Window Management //

#If A_PriorKey == "RWin" and !WinActive("ahk_group ExplorerUI")

RWin:: PostMessage 0x112, 0xF020,,, A	; Minimize the active window

#If (RWinQ, DllCall("QueryPerformanceCounter", "Int64*", RWinQ)) - RWinP << 1 < freq and A_PriorKey == "RWin" and !WinActive("ahk_group ExplorerUI")

>+RWin Up:: GetKeyState("RShift", "P") and DllCall("PostMessage", "Ptr", GetFirstWindow(), "uInt", 0x112, "uInt", 0xF020, "Int", 0)
>^RWin Up:: GetKeyState("RCtrl", "P") and WinClose("A")		; Close the active window
>!RWin Up:: GetKeyState("RAlt", "P") and ActivateNext()		; Move active window to the bottom of the Z-order & activate next window

#If

RWin:: return
>#Space:: WinExist("A") and (WinGet("MinMax") ? PostMessage(0x112, 0xF120) : PostMessage(0x112, 0xF030))	; Toggle Maximize/Restore active window
>#Up:: WinSet AlwaysOnTop,, A				; Toggle topmost status of the active window
>#Backspace:: PostMessage 0x112, 0xF100, 32,, A		; Window Shortcut Menu



; // System Volume //

#+SC053:: Send {Volume_Mute}
#+NumpadAdd:: Send {Volume_Up}
#+NumpadSub:: Send {Volume_Down}



; // Alt Google Chrome Url //

#!+g:: (AltUrl := CopySel()) <> "" or InputGui(AltUrl, "Google URL",, InputUrl, 16) ? (Open("chrome.exe """ AltUrl """ " AltDataP), InputUrl := AltUrl)



; / AutoHotkey Command Line /

#MaxThreadsPerHotkey 2

SC054:: InputCommand()

InputCommand() {
	static CmdRegEx := "(*UCP)(?P<Set>[\w@#$]+)(?:\[(?P<SKey>(&Set))])?\s*:=\s*(?:(?P<Num>(?:0x)?\d+)"
		. "|(?:(?P<Get>(&Set))(?:\[(?P<GKey>(&Set)(?:,(&Set))*)])?)|(?P<Str>"".*""))\s*$", NewCmd
	global Commands
	InputGui(NewCmd, "AutoHotkey Command", "Write the AutoHotkey script you want to run.", 1, 80, Commands, 400) == true
		? RegExMatch(NewCmd, CmdRegEx, Var)
			? (VarSKey == "")
				? (VarGKey == "")
					? (VarGet == "ClipboardAll")
						? SaveClipboard(%VarSet%)
					: %VarSet% := VarNum == "" ? VarGet == "" ? VarStr == """""" or VarStr == "" ? "" : StrReplace(SubStr(VarStr, 2, -1), """""", """") : %VarGet% : VarNum
				: %VarSet% := %VarGet%[VarGKey]
			: %VarSet%[VarSKey] := VarGKey == "" ? %VarGet% : %VarGet%[VarGKey]
		: (GetKeyState("Ctrl", "P") ? GetKeyState("Shift", "P") ? DynaRunScriptAdmin32(InputCommandScriptDecode(NewCmd), "Dynamic AutoHotkey Script")
			: DynaRunScript32(InputCommandScriptDecode(NewCmd), "Dynamic AutoHotkey Script")
			: GetKeyState("Shift", "P") ? DynaRunScriptAdmin64(InputCommandScriptDecode(NewCmd), "Dynamic AutoHotkey Script")
			: DynaRunScript64(InputCommandScriptDecode(NewCmd), "Dynamic AutoHotkey Script"), SaveItem(NewCmd, Commands, 4096, "Commands"))
}

InputCommandScriptDecode(EncodedScript) {
	return StrReplace(StrReplace(StrReplace(RegExReplace(StrReplace(StrReplace(StrReplace(StrReplace(EncodedScript, "", "@"), "\\\\", "d"), "\\;", "s"), "\\")
		, " *; *", "`n"), "s", ";"), "d", "\\"), "@", "")
}



; // Alternate Run Dialog //

#^r:: InputGui(RunTarget, "Run", "Type the name of the program, folder, file, or Internet resource you want to access.", 1, 80, RunList)
	and (GetKeyState("Shift", "P") ? PipeRunAdmin(Deref(RunTarget)) : RunApp(Deref(RunTarget)), SaveItem(RunTarget, RunList, 50, "RunList"))

#MaxThreadsPerHotkey 1



; // Desktop Mode Power Scheme Context Menu Item //
/*
AHK_NOTIFYICON(wParam, lParam) {
	
	static LastButtonMode := true, EnterDesktop := "Enter Desktop Mode", ExitDesktop := "Exit Desktop Mode"
	global DisableScreensaver
	If (lParam <> 0x205)
		return
	If DisableScreensaver {
		If (LastButtonMode == true) {
			Menu Tray, Rename, %EnterDesktop%, %ExitDesktop%
			LastButtonMode := false
		} else if (LastButtonMode == 2) {
			Menu Tray, Enable, %ErrorDesktopName%
			Menu Tray, Rename, %ErrorDesktopName%, %ExitDesktop%
			LastButtonMode := false
		}
	} else
		If (LastButtonMode == false) {
			Menu Tray, Rename, %ExitDesktop%, %EnterDesktop%
			LastButtonMode := true
		} else if (LastButtonMode == 2) {
			Menu Tray, Enable, %ErrorDesktopName%
			Menu Tray, Rename, %ErrorDesktopName%, %EnterDesktop%
			LastButtonMode := true
		}
	
}
*/

ToggleDesktopMode(MenuItemName, ItemPos, MenuName) {
	
	static PowerRequestObject, ReasonStringDesktop := "User Desktop Mode Active", ReasonStringSystem := "System Desktop Mode Active"
		, EnterDesktopUser := "Enter User Desktop Mode", EnterDesktopSystem := "Enter System Desktop Mode", ExitDesktop := "Exit Desktop Mode"
	static (ReasonContextUser,  VarSetCapacity(ReasonContextUser, A_PtrSize + 8, 0), NumPut(1, ReasonContextUser, 4, "uInt")
		, NumPut(&ReasonStringDesktop, ReasonContextUser, 8, "Ptr"))
	static (ReasonContextSystem, VarSetCapacity(ReasonContextSystem, A_PtrSize + 8, 0), NumPut(1, ReasonContextSystem, 4, "uInt")
		, NumPut(&ReasonStringSystem, ReasonContextSystem, 8, "Ptr"))
	global DisableScreensaver, MainScriptIni
	
	Switch MenuItemName {
		case EnterDesktopUser:
			If PowerRequestObject
				DllCall("PowerClearRequest", "Ptr", PowerRequestObject, "Int", DisableScreensaver)
			If (DisableScreensaver = 1) {
				Menu PowerSettings, Delete, System Desktop Mode Active
				Menu PowerSettings, Insert, Enter System Desktop Mode, 1, ToggleDesktopMode
			} PowerRequestObject := DllCall("PowerCreateRequest", "Str", ReasonContextUser, "Ptr")
			, DllCall("PowerSetRequest", "Ptr", PowerRequestObject, "Int", 0), DisableScreensaver := 0
			Menu PowerSettings, Delete, Enter User Desktop Mode
			Menu PowerSettings, Insert, User Desktop Mode Active, 0, DesktopLabel, +Radio
			Menu PowerSettings, Check, User Desktop Mode Active
			Menu PowerSettings, Add, Exit Desktop Mode
		case EnterDesktopSystem:
			If PowerRequestObject
				DllCall("PowerClearRequest", "Ptr", PowerRequestObject, "Int", DisableScreensaver)
			If (DisableScreensaver = 0) {
				Menu PowerSettings, Delete, User Desktop Mode Active
				Menu PowerSettings, Insert, Enter User Desktop Mode, 0, ToggleDesktopMode
			} PowerRequestObject := DllCall("PowerCreateRequest", "Str", ReasonContextSystem, "Ptr")
			, DllCall("PowerSetRequest", "Ptr", PowerRequestObject, "Int", 1), DisableScreensaver := 1
			Menu PowerSettings, Delete, Enter System Desktop Mode
			Menu PowerSettings, Insert, System Desktop Mode Active, 1,, +Radio
			Menu PowerSettings, Check, System Desktop Mode Active
			Menu PowerSettings, Add, Exit Desktop Mode
		case ExitDesktop:
			Switch DisableScreensaver {
				case 0:
					Menu PowerSettings, Delete, User Desktop Mode Active
					Menu PowerSettings, Insert, Enter User Desktop Mode, 0, ToggleDesktopMode
				case 1:
					Menu PowerSettings, Delete, System Desktop Mode Active
					Menu PowerSettings, Insert, Enter System Desktop Mode, 1, ToggleDesktopMode
				case -1: return
			} DllCall("PowerClearRequest", "Ptr", PowerRequestObject, "Int", DisableScreensaver)
			, DllCall("CloseHandle", "Ptr", PowerRequestObject), DisableScreensaver := -1
			Menu PowerSettings, Delete, Exit Desktop Mode
	} IniWrite % DisableScreensaver, %MainScriptIni%, Settings, DisableScreensaver
	
}

DesktopLabel(MenuItemName, ItemPos, MenuName) {
	return
}

/*
ToggleDesktopMode(MenuItemName, ItemPos, MenuName) {
	
	static LastActiveSchemeCLSID, EnterDesktop := "Enter Desktop Mode", ExitDesktop := "Exit Desktop Mode"
	global ScreensaverDisabled
	(MenuItemName == EnterDesktop) ? (LastActiveSchemeCLSID and DllCall("LocalFree", "Ptr", LastActiveSchemeCLSID)
	  , DllCall("PowrProf\PowerGetActiveScheme", "Ptr", 0, "Ptr*", LastActiveSchemeCLSID), GetPowerSchemeCLSID("Desktop Mode", DesktopModeCLSID)
	  , DllCall("PowrProf\PowerSetActiveScheme", "Ptr", 0, "Str", DesktopModeCLSID))
  : (MenuItemName == ExitDesktop) ? (DllCall("PowrProf\PowerReadFriendlyName", "Ptr", 0, "Ptr", LastActiveSchemeCLSID, "Ptr", 0, "Ptr", 0, "Ptr", 0, "uInt*", 0) == 0
	  ? DllCall("PowrProf\PowerSetActiveScheme", "Ptr", 0, "Ptr", LastActiveSchemeCLSID) : DllCall("PowrProf\PowerSetActiveScheme", "Ptr", 0, "Str", "翚豞䪖薚谺屣")
	  , DllCall("LocalFree", "Ptr", LastActiveSchemeCLSID), LastActiveSchemeCLSID := "") : ""
	
}
*/


; // Window Properties //

;#Include Window Properties.ahk



; // Window Cache //

;#Include Window Cache.ahk


ActivateNext(ByRef hWnd := "") {
	If !hWnd := WinNext("A")
		return
	WinSet Bottom
	WinActivate ahk_id %hWnd%
	return hWnd
}

CharMulti(Char, Length) {
	VarSetCapacity(CharStr, Length << 1, 32)
  return StrGet(DllCall("msvcrt\_wcsnset", "Str", CharStr, "uInt", Char, "uInt", Length, "CDecl Ptr"), Length)
}

ChromeApp(Location, UseDefault := false) {
	static Chrome := """C:\Program Files\Google\Chrome\Application\chrome.exe""  "
	return RunApp(Chrome (UseDefault ? "--profile-directory=Default " : "") (Location ~= "[a-p]{32}" ? "--app-id=" Location : "-app=" StrReplace(Location, " ", "%20")))
}

CopySel(ByRef Ctrl := 0, ByRef EditClass := "", ByRef AddlInfo := 0, ByRef Process := 0, ByRef start := 0, ByRef end := 0) {
	static (GuiThreadInfo, VarSetCapacity(GuiThreadInfo, 48), NumPut(48, GuiThreadInfo)), Focus := 8 + A_PtrSize	;F, , DllCall("QueryPerformanceFrequency", "Int64*", F)
	;, ClassList := {Edit: 1, Scintilla: 2, RICHEDIT: 3}
	;global PrevClip	;, PrevBak := PrevClip
	DllCall("GetGUIThreadInfo", "uInt", 0, "Str", GuiThreadInfo)	; Get focused control & active window handles
	If (EditClass := RealGetWindowClass(Ctrl := NumGet(GuiThreadInfo, Focus))) == "Scintilla"
		return SciGetSelText(Ctrl, AddlInfo, Process)	;, Type := 2
	If DllCall("SendMessage", "Ptr", Ctrl, "uInt", 176, "uInt*", start, "uInt*", end) {	; 176 = EM_GETSEL
	;	DllCall("GetClassName", "Ptr", Ctrl, "Str", EditClass, "Int", 10)
	; , RegExMatch(StrGet(ClassAddress), "A)Edit|Scintilla|RICHEDIT", EditClass)
		If (start = end)
			 return
		If AddlInfo := DllCall("SendMessage", "Ptr", Ctrl, "uInt", 1114, "Int", 0, "Int", 0)	;InStr(EditClass, "RichEdit")
			return CopySelGetSelText(Ctrl, end - start)
		ClipBak := ClipboardAll										; Back up the clipboard
		DllCall("SendMessage", "uInt", Ctrl, "uInt", 0x301, "Int", 0, "Int", 0)	; 0x301 = WM_COPY
		return Clipboard, Clipboard := ClipBak
	} ClipBak := ClipboardAll										; Back up the clipboard
	Clipboard := ""
	If DllCall("SendMessage", "uInt", Ctrl, "uInt", 0x319, "uInt", 0, "uInt", 0x240000) = 0 {	; 0x319 = WM_APPCOMMAND, 0x240000 = APPCOMMAND_COPY
		SendInput ^c
		EditClass := ""
	} else EditClass := 0
	;DllCall("QueryPerformanceCounter", "Int64*", P)
	ClipWait 0, 1
	;DllCall("QueryPerformanceCounter", "Int64*", Q), Time := (Q - P) / F
   return Clipboard, Clipboard := ClipBak	;, PrevClip := PrevBak
}

DynaRunScript32(script, pipename := "", WorkingDir := "") {
	static defaults := "#NoEnv`nSetBatchLines -1`nSendMode Input`n`nMenu Tray, Tip, % ""{:s} (PID: "" DllCall(""GetCurrentProcessId"", ""uInt"") "")""`n`n{:s}"
	DllCall("QueryPerformanceCounter", "Int64*", timestamp), pipepath := "\\.\pipe\" (pipename = "" ? pipename := "Dynamic AutoHotkey Script [x86]" : pipename .= " [x86]")
		. " " Format("{:x}", timestamp)
	If (Pipe_Ga := DllCall("CreateNamedPipe", "Str", pipepath, "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr")) = -1
		return -1
	If (Pipe := DllCall("CreateNamedPipe", "Str", pipepath, "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr")) = -1
		return -2, DllCall("CloseHandle", "Ptr", Pipe_Ga)
	Run "%A_AhkPath%\..\AutoHotkeyU32_UIA.exe" /force /CP65001 "%pipepath%", %WorkingDir%, UseErrorLevel, PID
	If A_LastError {
		DllCall("CloseHandle", "Ptr", Pipe_Ga), DllCall("CloseHandle", "Ptr", Pipe)
		If (A_LastError = 1223)
			return -5
		MsgBox 0x40010, DynaRunScript Error, % "Error running pipe:`n`n" pipepath "`n`nError " A_LastError " - " GetErrorMsg(A_LastError)
		return -3
	} DllCall("ConnectNamedPipe", "Ptr", Pipe_Ga, "Ptr", 0), DllCall("ConnectNamedPipe", "Ptr", Pipe, "Ptr", 0), DllCall("CloseHandle", "Ptr", Pipe_Ga)
	return FileOpen(Pipe, "h", "UTF-8").Write(Format(defaults, pipename, script)) ? PID : -4, DllCall("CloseHandle", "Ptr", Pipe)
}

DynaRunScript64(script, pipename := "", WorkingDir := "") {
	static defaults := "#NoEnv`nSetBatchLines -1`nSendMode Input`n`nMenu Tray, Tip, % ""{:s} (PID: "" DllCall(""GetCurrentProcessId"", ""uInt"") "")""`n`n{:s}"
	DllCall("QueryPerformanceCounter", "Int64*", timestamp), pipepath := "\\.\pipe\" (pipename = "" ? pipename := "Dynamic AutoHotkey Script [x64]" : pipename .= " [x64]")
		. " " Format("{:x}", timestamp)
	If (Pipe_Ga := DllCall("CreateNamedPipe", "Str", pipepath, "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr")) = -1
		return -1
	If (Pipe := DllCall("CreateNamedPipe", "Str", pipepath, "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr")) = -1
		return -2, DllCall("CloseHandle", "Ptr", Pipe_Ga)
	Run "%A_AhkPath%\..\AutoHotkeyU64_UIA.exe" /force /CP65001 "%pipepath%", %WorkingDir%, UseErrorLevel, PID
	If A_LastError {
		DllCall("CloseHandle", "Ptr", Pipe_Ga), DllCall("CloseHandle", "Ptr", Pipe)
		If (A_LastError = 1223)
			return -5
		MsgBox 0x40010, DynaRunScript Error, % "Error running pipe:`n`n" pipepath "`n`nError " A_LastError " - " GetErrorMsg(A_LastError)
		return -3
	} DllCall("ConnectNamedPipe", "Ptr", Pipe_Ga, "Ptr", 0), DllCall("ConnectNamedPipe", "Ptr", Pipe, "Ptr", 0), DllCall("CloseHandle", "Ptr", Pipe_Ga)
	return FileOpen(Pipe, "h", "UTF-8").Write(Format(defaults, pipename, script)) ? PID : -4, DllCall("CloseHandle", "Ptr", Pipe)
}

DynaRunScriptAdmin32(script, pipename := "", WorkingDir := "") {
	static defaults := "#NoEnv`nSetBatchLines -1`nSendMode Input`n`nMenu Tray, Tip, % ""{:s} (PID: "" DllCall(""GetCurrentProcessId"", ""uInt"") "")""`n`n"
	DllCall("QueryPerformanceCounter", "Int64*", timestamp), pipepath := "\\.\pipe\" (pipename = "" ? pipename := "Dynamic AutoHotkey Script [x86 - Admin]"
		: pipename .= " [x86 - Admin]") " " Format("{:x}", timestamp)
	If (Pipe_Ga := DllCall("CreateNamedPipe", "Str", pipepath, "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr")) = -1
		return -1
	If (Pipe := DllCall("CreateNamedPipe", "Str", pipepath, "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr")) = -1
		return -2, DllCall("CloseHandle", "Ptr", Pipe_Ga)
	Run *RunAs "%A_AhkPath%\..\AutoHotkeyU32_UIA.exe" /force /CP65001 "%pipepath%", %WorkingDir%, UseErrorLevel, PID
	If A_LastError {
		DllCall("CloseHandle", "Ptr", Pipe_Ga), DllCall("CloseHandle", "Ptr", Pipe)
		If (A_LastError = 1223)
			return -5
		MsgBox 0x40010, DynaRunScript Error, % "Error running pipe:`n`n" pipepath "`n`nError " A_LastError " - " GetErrorMsg(A_LastError)
		return -3
	} DllCall("ConnectNamedPipe", "Ptr", Pipe_Ga, "Ptr", 0), DllCall("ConnectNamedPipe", "Ptr", Pipe, "Ptr", 0), DllCall("CloseHandle", "Ptr", Pipe_Ga)
	return FileOpen(Pipe, "h", "UTF-8").Write(Format(defaults, pipename) script) ? PID : -4, DllCall("CloseHandle", "Ptr", Pipe)
}

DynaRunScriptAdmin64(script, pipename := "", WorkingDir := "") {
	static defaults := "#NoEnv`nSetBatchLines -1`nSendMode Input`n`nMenu Tray, Tip, % ""{:s} (PID: "" DllCall(""GetCurrentProcessId"", ""uInt"") "")""`n`n"
	DllCall("QueryPerformanceCounter", "Int64*", timestamp), pipepath := "\\.\pipe\" (pipename = "" ? pipename := "Dynamic AutoHotkey Script [x64 - Admin]"
		: pipename .= " [x64 - Admin]") " " Format("{:x}", timestamp)
	If (Pipe_Ga := DllCall("CreateNamedPipe", "Str", pipepath, "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr")) = -1
		return -1
	If (Pipe := DllCall("CreateNamedPipe", "Str", pipepath, "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr")) = -1
		return -2, DllCall("CloseHandle", "Ptr", Pipe_Ga)
	Run *RunAs "%A_AhkPath%\..\AutoHotkeyU64_UIA.exe" /force /CP65001 "%pipepath%", %WorkingDir%, UseErrorLevel, PID
	If A_LastError {
		DllCall("CloseHandle", "Ptr", Pipe_Ga), DllCall("CloseHandle", "Ptr", Pipe)
		If (A_LastError = 1223)
			return -5
		MsgBox 0x40010, DynaRunScript Error, % "Error running pipe:`n`n" pipepath "`n`nError " A_LastError " - " GetErrorMsg(A_LastError)
		return -3
	} DllCall("ConnectNamedPipe", "Ptr", Pipe_Ga, "Ptr", 0), DllCall("ConnectNamedPipe", "Ptr", Pipe, "Ptr", 0), DllCall("CloseHandle", "Ptr", Pipe_Ga)
	return FileOpen(Pipe, "h", "UTF-8").Write(Format(defaults, pipename) script) ? PID : -4, DllCall("CloseHandle", "Ptr", Pipe)
}

EscapeText(Text, String) {
	return StrReplace(StrReplace(StrReplace(Text, "", ""), "", ""), String, "")
}

FastStrRepeat(String, Count) {
	If (Count <= 0)
		return
	VarSetCapacity(DestString, Count * (Length := StrLen(String)) + 1 << 1)
	return DllCall("msvcrt\wcsncat", "Str", DestString := String, "Str", DestString, "Ptr", Length * (Count - 1), "CDecl WStr")
}

FormatDateTime(ByRef SystemTime, Format) {
	static ExtraSpace := 10 << (A_IsUnicode = true)
	CaseSense := A_StringCaseSense
	StringCaseSense On
	Size := VarSetCapacity(DateTime, VarSetCapacity(Format, -1) + ExtraSpace)
	If (Flags := DateTimeFormat(Format)) == 3
		DllCall("GetTimeFormat", "uInt", 0x400, "uInt", 0, "Str", SystemTime, "Str", FormatMsTt(SystemTime, Format), "Str", DateTime, "uInt", Size)
	  , DllCall("GetDateFormat", "uInt", 0x400, "uInt", 0, "Str", SystemTime, "Str", DateTime, "Str", DateTime, "uInt", Size)
	else If (Flags == 2)
		DllCall("GetTimeFormat", "uInt", 0x400, "uInt", 0, "Str", SystemTime, "Str", FormatMs(SystemTime, Format), "Str", DateTime, "uInt", Size)
	else If (Flags == 1)
		DllCall("GetDateFormat", "uInt", 0x400, "uInt", 0, "Str", SystemTime, "Str", FormatMs(SystemTime, Format), "Str", DateTime, "uInt", Size)
	else DateTime := FormatMs(SystemTime, Format)
	StringCaseSense %CaseSense%
	return DateTime
}

DateTimeFormat(Format) {
	Flags := 0
	Loop Parse, Format, '
		If (A_Index & 1 && A_LoopField <> "") {
			If A_LoopField contains H,h,m,s,t
				If A_LoopField contains M,d,y,g
					return 3
				else Flags |= 2
			else If A_LoopField contains M,d,y,g
					Flags |= 1
			If (Flags = 3)
				return 3
		}
	return Flags
}

FormatMs(ByRef SystemTime, Format) {
	Loop Parse, Format, '
		NewFormat .= "'" (A_Index & 1 && A_LoopField <> "" && InStr(A_LoopField, "n", true) ? Format(StrReplace(StrReplace(StrReplace(A_LoopField, "nnn", "{1:03u}"), "nn", "{1:02u}")
			, "n", "{1:u}"), NumGet(SystemTime, 14, "uShort")) : A_LoopField)
	return SubStr(NewFormat, 2)
}

FormatMsTt(ByRef SystemTime, Format) {
	Loop Parse, Format, '
		NewFormat .= (A_Index & 1 && A_LoopField <> "" ? StrReplace(InStr(A_LoopField, "n", true) ? Format(StrReplace(StrReplace(StrReplace(A_LoopField, "nnn", "{1:03u}")
			, "nn", "{1:02u}"), "n", "{1:u}"), NumGet(SystemTime, 14, "uShort")) : A_LoopField, "tt", "''''tt''''") : A_LoopField) "'''"
	return SubStr(NewFormat, 1, -3)
}

GetAppStartTime(hWnd, Format := "M/d/yyyy h꞉mm꞉ss.nnn tt", ByRef PID := 0) {
	If DllCall("GetWindowThreadProcessId", "Ptr", hWnd, "uInt*", PID)
		return GetProcessStartTime(PID, Format)
}

GetLocalTime(Format := "M/d/yyyy h꞉mm꞉ss.nnn tt") {	; , ByRef Time := ""
	static (VarSetCapacity(LocalTime, 16))
	DllCall("GetLocalTime", "Str", LocalTime)	; VarSetCapacity(Time, 16), 
	return FormatDateTime(LocalTime, Format)	; , DllCall("GetLocalTime", "Str", Time)
}

GetProcessStartTime(PID, Format := "M/d/yyyy h꞉mm꞉ss.nnn tt", ByRef Process := "") {
	return GetProcessStartTimeStruct(PID, SystemTime, Process) ? (FormatDateTime(SystemTime, Format), IsByRef(Process) or DllCall("CloseHandle", "Ptr", Process)) : ""
}

GetVolumeObject(Param) {
    static IID_IASM2 := "{77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F}"
		 , IID_IASC2 := "{bfb7ff88-7239-4fc9-8fa2-07c950be9c6d}"
		 , IID_ISAV  := "{87CE5498-68D6-44E5-9215-6DA47EF883D8}"
    

    ; Turn empty into integer
    if !Param
        Param := 0
    else 
		; Get PID from process name
		if Param is not Integer
		{
			Process, Exist, %Param%
			Param := ErrorLevel
		}

    ; GetDefaultAudioEndpoint
    DAE := VA_GetDevice()
    
    ; activate the session manager
  , VA_IMMDevice_Activate(DAE, IID_IASM2, 0, 0, IASM2)
    
    ; enumerate sessions for on this device
  , VA_IAudioSessionManager2_GetSessionEnumerator(IASM2, IASE)
  , VA_IAudioSessionEnumerator_GetCount(IASE, Count)
    
    ; search for an audio session with the required name
    Loop, % Count {
        ; Get the IAudioSessionControl object
        VA_IAudioSessionEnumerator_GetSession(IASE, A_Index-1, IASC)
        
        ; Query the IAudioSessionControl for an IAudioSessionControl2 object
      , IASC2 := ComObjQuery(IASC, IID_IASC2), ObjRelease(IASC)
        
        ; Get the sessions process ID
      , VA_IAudioSessionControl2_GetProcessID(IASC2, SPID)
        
        ; If the process name is the one we are looking for
        if (SPID == Param) {
            ; Query for the ISimpleAudioVolume
            ISAV := ComObjQuery(IASC2, IID_ISAV), ObjRelease(IASC2)
            Break
        }
		
		ObjRelease(IASC2)
    }
	
    ObjRelease(IASE), ObjRelease(IASM2), ObjRelease(DAE)
	
    return ISAV
}

GroupCreate(GroupName, Rules*) {
	For Index, Rule in Rules
		GroupAdd % GroupName, % Rule
}

Hex(number) {
	return Format("{:s}{:#x}", number < 0 ? "-" : "", abs(number))
}

HttpQuery(Url, Timeout := -1) {
	(WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")).Open("HEAD", Url)
	If WebRequest.Send() or !WebRequest.WaitForResponse(Timeout)
		return
	;, DllCall("msvcrt\_vsnwprintf", Ptr, sAdd, Int, 24, Str, "%04hu%02hu/%02hu/%hu%02hu:%02hu:%02hu.%03hu", Ptr, Add)
	FileAppend % "Error " WebRequest.Status "  " GetLocalTimeString() "  " Url "`r`n`r`n" WebRequest.GetAllResponseHeaders() "`r`n`r`n`r`n"
		, %A_MyDocuments%\AutoHotkey\Status Info\HttpQuery Response Log.txt, UTF-8
   return WebRequest.Status
} ;DllCall("msvcrt\_vsnwprintf", UIntP, sAdd, Int, 3, Str, "%hu", Ptr, a)

IniReadUnescape(File, Section, Key := "", Default := " ") {
	IniRead EscapedText, %File%, %Section%, %Key%, %Default%
	return UnescapeText(EscapedText, "`n")
}

IniWriteEscape(Text, File, Section, Key := "") {
	IniWrite % EscapeText(Text, "`n"), %File%, %Section%, %Key%
}

InputBox(ByRef Output, Title := "AutoHotkey Input", Text := "", Default := "", Width := "", Height := 131, Hide := "", X := "", Y := "", Timeout := "") {
	InputBox UserInput, %Title%, %Text%, %Hide%, Width, Text == "" ? 106 : Height, X, Y,, Timeout, %Default%
return !ErrorLevel and (Output := UserInput) <> ""
}

InputGui(ByRef UserInput, Title := "", Text := "", Default := "", Options := 0, List := "", Width := 320, Font := "", Rows := 10, X := "", Y := "", Timeout := "") {

	static Caption, OK, Cancel, MaxWidth := A_ScreenWidth << 2 ;, GuiList := []	;  (+MaxSize +MaxSize" MaxWidth ")
	Gui % "InputGui" &UserInput ":+LastFoundExist"
	IfWinExist
	{	WinActivate
		return 2
	} ;If GuiList.HasKey(&UserInput) and DllCall("IsWindow", "Ptr", GuiList[&UserInput])
		;return "Activate: " (DllCall("SwitchToThisWindow", "Ptr", GuiList[&UserInput]) ? "true" : "false")
	If (Title = "")
		Title := A_ScriptName
	Gui % "InputGui" &UserInput ":New", % "+LastFound +LabelInputGui +HwndGuiID" (Options & 16 ? " +AlwaysOnTop" : "")
		. " +Delimiter`n " (Options & 128 ? "+MinSize124x +Resize" : "") " -MaximizeBox", %Title%
	;GuiList[&UserInput] := GuiID
	Gui Font, s9 w400, Segoe UI
	If (Text <> "")
		Gui Add, Text, % "x8 w" Width - 16 (Options & 1 ? " Center" : "") " vCaption", %Text%
	If (Font <> "") and ParseFont(Font, Face, Size, Weight) {
		Gui Font, s%Size% w%Weight%, %Face%
		InputGuiEdit(UserInput, Width - 12, Default, List, Options, Rows)
		Gui Font, s9 w400, Segoe UI
	} else InputGuiEdit(UserInput, Width - 12, Default, List, Options, Rows)
	Gui Add, Button, % "x" (cx := (Width << 1) // 5 - 47) " w60 h23 Default vOK gInputGuiOK", OK	; (cx := round((Width - 116 << 1) / 5)) - 1 ; (s := (Width - 120) // 5) << 1
	Gui Add, Button, % "x" Width - (cx + 60) " yp w60 h23 vCancel gInputGuiCancel", Cancel	; Width - 59 - cx ; Width - (s + 30 << 2)
	Gui Show, % "w" Width (X | 1 ? " x" X : "") (Y | 1 ? " y" Y : "")
	WinWaitClose,,, % Timeout
	If ErrorLevel
		Gui Destroy
	return OK	;, GuiList.Delete(&UserInput)
	
	InputGuiOK:
		Gui Submit
		OK := not (Options & 32 and UserInput == "")
		Gui Destroy
	return
	
	InputGuiCancel:
	InputGuiClose:
	InputGuiEscape:
		OK := false
		If (Options & 8)
			Gui Submit
		Gui Destroy
	return
	
}

InputGuiSize(GuiHwnd, EventInfo, Width, Height) {
	
	If (EventInfo == true)
		return
	GuiControl MoveDraw, Static1, % "w" Width - 16
	GuiControl MoveDraw, Edit1, % "w" Width - 12
	GuiControl MoveDraw, Button1, % "x" x := (Width << 1) // 5 - 47	; (s := (Width - 120) // 5) << 1
	GuiControl MoveDraw, Button2, % "x" Width - (x + 60)	; Width - (s + 30 << 1)
	
}


InputGuiEdit(ByRef UserInput, Width, Default, List, Options, Rows) {
	(Delim := InStr(Default, "`n")) and CueString := SubStr(Default, 1, Delim - 1)	;, Default := SubStr(Default, Sep + 1)
	If (Options & 4) {
		Gui Add, Edit, % "x6 r1 w" Width " WantTab Password HwndInputGuiHwnd vUserInput", % Delim > 0 ? SubStr(Default, Delim + 1) : Default
		(Delim) or DllCall("SendMessage", "Ptr", InputGuiHwnd, "uInt", 0x1501, "Int", true, "Str", CueString)
	} else If (List <> "") {
		If (Options & 64)
			Gui Add, ComboBox, % "x6 r" Rows " w" Width " Choose" (Default | 1 ? Default : 1) (Options & 2 ? " +Sort" : "") " HWndInputGuiHwnd vUserInput", %List%
		else {
			Gui Add, ComboBox, % "x6 r" Rows " w" Width (Options & 2 ? " +Sort" : "") " HwndInputGuiHwnd vUserInput", %List%
			DllCall("SetDlgItemText", "Ptr", InputGuiHwnd, "Int", 1001, "Str", Default)
		} (Delim) or DllCall("SendDlgItemMessage", "Ptr", InputGuiHwnd, "Int", 1001, "uInt", 0x1501, "Int", true, "Str", CueString)
	  ;, Rows == 30 or DllCall("SendMessage", "Ptr", InputGuiHwnd, "uInt", 0x1701, "uInt", Rows, "Int", 0)
	} else Gui Add, Edit, x6 r1 w%Width% WantTab vUserInput, %Default%
}

ParseFont(Font, ByRef Face := "", ByRef Size := "", ByRef Weight := "") {
	static WeightValue := {Thin: 100, Extra Light: 200, Extralight: 200, UltraLight: 200, Ultra Light: 200, Light: 300, Normal: 400, Regular: 400, Medium: 500
		, Semibold: 600, Bold: 700, Extrabold: 800, Extra Bold: 800, Heavy: 900, Black: 1000, Max: 1000, Maximum: 1000}
	If (Font := StrSplit(Font, ":", " `t`n`r")).1 or Font.2 | 1 or Font.3
		return true, Face := Font.1 | 1 ? "Segoe UI" : font.1, Size := font.2 | 1 ? font.2 | 0 : 9
			, Weight := font.3 | 1 ? font.3 | 0 : font.3 <> "" and WeightValue.HasKey(font.3) ? WeightValue[font.3] : 400
	 return false
}

ListScripts(Dir) {
	Loop Files, %Dir%\*.ahk
		Names .= SubStr(A_LoopFileName, 1, -4) "`n"
	return SubStr(Names, 1, -1)
}

Msg(Text, Title := "AutoHotkey", Options := 0, Timeout := 0) {
	MsgBox % Options | (DllCall("GetWindowLong", "Ptr", DllCall("GetForegroundWindow"), "Int", -20) & 8) << 15, % Title, % Text, % Timeout
   return Text		; DllCall("MessageBox", uInt, 0, Str, Text, Str, Title, uInt, 0x50000 | Options)
}

Now(Format := "M/d/yyyy h꞉mm꞉ss.nnn tt") {
	static (VarSetCapacity(LocalTime, 16))
	DllCall("GetLocalTime", "Str", LocalTime)
	return FormatDateTime(LocalTime, Format)
}

Open(Target, WinSize := "", ByRef Pid := "") {
	Run %Target%,, %WinSize% UseErrorLevel, Pid
	If A_LastError {
		MsgBox 0x10, Error %A_LastError%, % Target "`n" GetLastErrorMsg()
		 return true
	} return 0
}

OpenNotepad(Title := "", WorkingDir := "") {
	WScript := ComObjCreate("WScript.Shell")
	Loop 1 {
		Loop 1 {
			Run notepad, %WorkingDir%, hide UseErrorLevel, PID
			If ErrorLevel
				Break 2
			If (PID = "")
				return 0, AsyncMsgBox("Notepad cannot be shown.", "Notepad Error", 0x10)
			NotepadWait := WScript.Exec("AutoHotkey.exe /ErrorStdOut *")
			If (Title = "") or not Process := DllCall("OpenProcess", "uInt", 56, "Int", false, "Ptr", NotepadWait.ProcessID, "Ptr")
				Break
			If not Address := DllCall("VirtualAllocEx", "Ptr", Process, "Ptr", 0, "Ptr", (TitleLength := 2 * StrLen(Title)) + 2, "uInt", 0x3000, "uInt", 4, "Ptr") {
				DllCall("CloseHandle", "Ptr", Process)
				Break
			} If not DllCall("WriteProcessMemory", "Ptr", Process, "Ptr", Address, "Str", Title, "Ptr", TitleLength, "Ptr", 0) {
				DllCall("VirtualFreeEx", "Ptr", Process, "Ptr", Address, "Ptr", 0, "uInt", 0x8000)
			  , DllCall("CloseHandle", "Ptr", Process)
				Break
			} NotepadWait.StdIn.Write("#NoEnv`n#NoTrayIcon`nSetBatchLines -1`n`nDetectHiddenWindows On`nWinWait ahk_pid " PID ",, 60`nIf ErrorLevel`n`treturn`n"
			  . "DllCall(""SendDlgItemMessage"", ""Ptr"", WinExist(), ""Int"", 15, ""uInt"", 203, ""uInt"", 1, ""uInt*"", 16)`n"
			  . "WinSetTitle % StrGet(" Address ") "" - Notepad""`nWinShow`nWinActivate")
			, NotepadWait.StdIn.Close()
			return PID
		} NotepadWait.StdIn.Write("#NoEnv`n#NoTrayIcon`nSetBatchLines -1`n`nDetectHiddenWindows On`nWinWait ahk_pid " PID ",, 60`nIf ErrorLevel`n`treturn`n"
			  . "DllCall(""SendDlgItemMessage"", ""Ptr"", WinExist(), ""Int"", 15, ""uInt"", 203, ""uInt"", 1, ""uInt*"", 16)`nWinShow`nWinActivate")
		, NotepadWait.StdIn.Close()
		return PID
	} If (A_LastError = 1223)
		return -2
	If (A_LastError = 2)
		AsyncMsgBox("Notepad is missing.", "Notepad Missing", 0x10)
	else AsyncMsgBox("There was an error running Notepad.`n`nError " A_LastError " - " GetErrorMsg(A_LastError), "Notepad Error", 0x10)
	return -1
}

OpenWith(File, Program, WorkingDir := "", WindowSize := "", ByRef PID := "", Timeout := 5) {
	Run "%Program%" "%File%", %WorkingDir%, %WindowSize% UseErrorLevel, PID
	return ErrorLevel
}

PipeRunAdmin(CommandLine, WorkingDir := "", ShowState := "", Wait := true) {
	static ScriptTemplate := FileOpen("Lib\PipeRun Script Template.txt", 0).Read()
	If (Pipe_Ga := DllCall("CreateNamedPipe", "Str", "\\.\pipe\AutoHotkeyAdminPipeScript", "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr", 0)) = -1
		return -1
	If (Pipe := DllCall("CreateNamedPipe", "Str", "\\.\pipe\AutoHotkeyAdminPipeScript", "uInt", 2, "uInt", 0, "uInt", 255, "uInt", 0, "uInt", 0, "Ptr", 0, "Ptr", 0)) = -1
		return -2, DllCall("CloseHandle", "Ptr", Pipe_Ga)
	Run *RunAs "%A_AhkPath%" /CP65001 \\.\pipe\AutoHotkeyAdminPipeScript,, UseErrorLevel, PID
	If A_LastError {
		If (A_LastError <> 1223)
			MsgBox 0x40010, PipeRunAdmin Error, % "Could not open pipe \\.\pipe\AutoHotkeyAdminPipeScript`n`nError " A_LastError " - " GetErrorMsg(A_LastError)
		return -3, DllCall("CloseHandle", "Ptr", Pipe_Ga), DllCall("CloseHandle", "Ptr", Pipe)
	} DllCall("CreatePipe", "Ptr*", Read, "Ptr*", Write, "Ptr", 0, "uInt", 4), DllCall("ConnectNamedPipe", "Ptr", Pipe_Ga, "Ptr", 0)
	, DllCall("CloseHandle", "Ptr", Pipe_Ga), DllCall("ConnectNamedPipe", "Ptr", Pipe, "Ptr", 0)
	If (FileOpen(Pipe, "h", "UTF-8").Write(Format(ScriptTemplate, AssignEsc(CommandLine), AssignEsc(WorkingDir), AssignEsc(ShowState), Wait!!, DllCall("GetCurrentProcessId"), Write))
		 , DllCall("CloseHandle", "Ptr", Pipe))
		return FileOpen(Read, "h").ReadInt(), DllCall("CloseHandle", "Ptr", Read)
	return -4, DllCall("CloseHandle", "Ptr", Read)
}

Reload(Param := true) {
	Send {Ctrl}
	Reload
	return Param
}

RunActivate(Program, WorkingDir := "", WindowSize := "") {
	IfWinExist ahk_exe %Program%
		return -2, DllCall("SwitchToThisWindow", "Ptr", WinExist())
	return RunApp(Program, WorkingDir, WindowSize)
}

RunApp(App, WorkingDir := "", WindowSize := "") {
	Run %App%, %WorkingDir%, %WindowSize% UseErrorLevel, PID
	If (ErrorLevel = 0) {
		If (PID == "")
			return -2
		If WindowSize not contains min,hide
			AppWaitActivate(PID)
		return PID
	} If (A_LastError = 1223)
		return -3
	return -1, AsyncMsgBox("There was an error running the specified target:`n`n" App "`n`n" A_LastError ": " GetErrorMsg(A_LastError), "RunApp Error", 0x10)
}

RunAppAdmin(Program, WorkingDir := "", WindowSize := "") {
	Run *RunAs %Program%, %WorkingDir%, %WindowSize% UseErrorLevel, PID
	If (ErrorLevel = 0) {
		If (PID == "")
			return 0
		If WindowSize not contains min,hide
			AppWaitActivate(PID)
		return PID
	} If (A_LastError <> 1223)
		MsgBox 0x10, RunApp Error, % "There was an error running the specified target:`n`n" Program "`n`n" A_LastError ": " GetErrorMsg(A_LastError)
	return -1
}

AppWaitActivate(PID, Wait := 60) {
	WScript := ComObjCreate("WScript.Shell")
  , AppWaitScript := WScript.Exec("AutoHotkey.exe /ErrorStdOut *")
  , AppWaitScript.StdIn.Write("#NoEnv`n#NoTrayIcon`nSetBatchLines -1`n`nWinWait ahk_pid " PID (Wait = 0 ? "" : ",, " Wait) "`nIf (ErrorLevel = 0)`n`tWinActivate")
  , AppWaitScript.StdIn.Close()
}

RunHelp(Name, File, Timeout := 5) {
	If HelpWin := DllCall("FindWindow", Str, "HH Parent", Str, Name) {
		DllCall("IsWindowVisible", uInt, HelpWin) or DllCall("ShowWindowAsync", uInt, HelpWin, Int, 5)
		WinActivate ahk_id %HelpWin%
	} else {
		Run hh.exe %File%,, UseErrorLevel, HelpPid
		If ErrorLevel
			return "Error: " A_LastError
		WinWait ahk_pid %HelpPid%,, % Timeout
		If !ErrorLevel
			WinActivate
		return HelpPid
	}
}

SaveClipboard(ByRef ClipVar) {
	ClipVar := ClipboardAll
  return ClipVar <> ""
}

SaveItem(Item, ByRef List, Max := 0, IniKey := "", MainScriptIni := "..\Main Script.ini") {
	Trim(Item, " `t`n`r") == "" or (List := SubStr(List := Item StrReplace("`n" List, "`n" Item) "`n", 1, Max | 0 ? InStr(List, "`n",,, Max | 0) - 1 : -1)
		, (IniKey == "") or IniWriteEscape(List, MainScriptIni, "Lists", IniKey))
}

SciNot(n, places := 15) {
	return (n < 0 ? "−" : "") round(abs(n) / 10**(P := floor(log(abs(n)))), places) " • 10" NumToSuper(P)
}

SelAffix(Left := "", Right := "") {
	; static cb := VarSetCapacity(ClassName, 20)
	If (Selection := CopySelEx(Ctrl, EditClass, AddlInfo, Process, Left, Right)) == ""
		return -2
	;StringReplace Left, Left, `%s, %String%, All
	;StringReplace Right, Right, `%s, %String%, All
	;If (NewStr := SubStr(String, 1, Start := StrLen(Left)) = Left && SubStr(String, 1 + End := -StrLen(Right)) = Right ? SubStr(String, Start + 1, End) : Left String Right) == "" {
	If IsObject(Selection)
		DllCall("SendMessage", "Ptr", Ctrl, "uInt" 2160, "Int", AddlInfo.true.Anchor, "Int", AddlInfo.true.Caret)
	If !RegExMatch(Selection, "Asi)(?P<SpaceLeft>(?:\s+|,)*?)(?P<Left>\Q" Left "\E)?(?P<Main>[^,\s](?:.*\S)?)(?(Left)(?P<Right>\Q" Right "\E))(?P<SpaceRight>(?:\s+|,)*)$", Match)
		return -1
	If (Match = Left Right) {
		If EditClass
			(EditClass == "Scintilla") ? DllCall("SendMessage", "Ptr", Ctrl, "uInt", 2180, "Int", 0, "Int", 0)	; 2170 = SCI_REPLACESEL
				: DllCall("SendMessage", "Ptr", Ctrl, "uInt", 0x303, "Int", 0, "Int", 0)	; 0x303 = WM_CLEAR
		else SendInput {Del}
		 return 0
	} NewStr := MatchLeft == "" ? (MatchSpaceLeft Left MatchMain Right MatchSpaceRight, Displ := 1 - StrPut(Right, "UTF-8"))
		: (MatchSpaceLeft MatchMain MatchSpaceRight, Displ := StrPut(Right, "UTF-8") - 1)
	If EditClass
		If (EditClass == "Scintilla") {
			If IsObject(AddlInfo) {
				DllCall("SendMessage", "Ptr", Ctrl, "uInt", 2686, "uInt", AddlInfo.Start, "uInt", AddlInfo.End)
				return SciSelReplaceTarget(Ctrl, Process, NewStr), DllCall("SendMessage", "Ptr", Ctrl, "uInt", 2556	; 2556 = SCI_SETEMPTYSELECTION
					, "Int", max(0, AddlInfo.Current + StrPut(NewStr, "UTF-8") - 1 - AddlInfo.End + Displ) + AddlInfo.Start, "Int", 0), DllCall("CloseHandle", "Ptr", Process)
			} return ReplaceSelUTF8(Ctrl, NewStr), DllCall("CloseHandle", "Ptr", Process)
		} else return EditReplaceSel(Ctrl, NewStr)
	ClipBack := ClipboardAll
	Clipboard := NewStr
	If (EditClass = 0)
		DllCall("SendMessage", "Ptr", Ctrl, "uInt", 0x319, "Int", 0, "uInt", 0x260000)
	else SendInput ^v
	Sleep 40	; Give system time to retrieve contents of the clipboard for pasting
	 return true, Clipboard := ClipBack
}

SciSelAffixAll(Left, Right, Ctrl, Selections, SelRanges) {
	DllCall("SendMessage", "Ptr", Ctrl, "uInt", 2606, "Int", 0, "Int", 0)
	For each, Selection in Selecions {
		If !RegExMatch(Selection, "Asi)(?P<SpaceLeft>(?:\s+|,)*?)(?P<Left>\Q" Left "\E)?(?P<Main>[^,\s](?:.*\S)?)(?(Left)(?P<Right>\Q" Right "\E))(?P<SpaceRight>(?:\s+|,)*)$", Match) {
			DllCall("SendMessage", "Ptr", Ctrl, "uInt", 2606, "Int", 0, "Int", 0)	; 2606 = SCI_ROTATESELECTION
			Continue
		} (Match = Left Right) ? DllCall("SendMessage", "Ptr", Ctrl, "uInt", 2170, "Int", 0, "Ptr", 0)	; 2170 = SCI_REPLACESEL
		: SciReplaceSel(Ctrl, MatchLeft == "" ? MatchSpaceLeft Left MatchMain Right MatchSpaceRight : MatchSpaceLeft MatchMain MatchSpaceRight)
		, DllCall("SendMessage", "Ptr", Ctrl, "uInt", 2606, "Int", 0, "Int", 0)	; 2606 = SCI_ROTATESELECTION
	}
}

SelAffixAdd(Left := "", Right := "", Select := false) {
	static (VarSetCapacity(ClassName, 18))
	NewStr := Left CopySel(hCtrl, Type,,, start) Right
	If Type
		return DllCall("GetClassName", uInt, hCtrl, Str, ClassName, Int, 10)
			, ClassName == "Scintilla" && (VarSetCapacity(NewStr, StrPut(CopyStr := NewStr, "UTF-8")), StrPut(CopyStr, &NewStr, "UTF-8"))
			, DllCall("SendMessage", uInt, hCtrl, uInt, 194, Int, 1, Str, NewStr)	; 194 = EM_REPLACESEL
			, Select && DllCall("SendMessage", uInt, hCtrl, uInt, 177, uInt, start, uInt, start + StrLen(NewStr))
	ClipBack := ClipboardAll
	Clipboard := NewStr
	If (Type = 0)
		DllCall("SendMessage", uInt, hCtrl, uInt, 0x319, Int, 0, uInt, 0x260000)
	else SendInput ^v
	Sleep 40
	Clipboard := ClipBack
	return
}

StrTitle(Title) {
	Title := RegExReplace(Trim(Title), "\s+", " ", #)
	StringUpper Title, Title, T
	Loop Parse, Title, %A_Space%
	{	If (A_Index = 1) {
			Title := A_LoopField
			Continue
		} If (A_Index > #) {
			Title .= " " A_LoopField
			return Title
		} If A_LoopField in A,An,And,But,By,From,In,Is,Nor,Of,Or,The,This,To
		{	StringLower Word, A_LoopField
			Title .= " " Word
		} else Title .= " " A_LoopField
	} return Title
}

UnescapeText(Text, String) {
	Loop Parse, Text, 
		UnescapedText .= A_Index & 1 ? StrReplace(A_LoopField, "", String) : A_LoopField == "" ? "" : A_LoopField
	 return UnescapedText
}

WinClose(WinTitle := "", WinText := "", ExcludeTitle := "", ExcludeText := "") {
	PostMessage 0x112, 0xF060,,, % WinTitle, % WinText, % ExcludeTitle, % ExcludeText
	return ErrorLevel
}

WinGet(Cmd, WinTitle := "", ByRef Attribute := "") {
	WinGet Attribute, %Cmd%, %WinTitle%
	return Attribute
}
Helgef
Posts: 4709
Joined: 17 Jul 2016, 01:02
Contact:

Re: Wrong Exit Reason Displayed on Script Reload

16 Jan 2020, 10:03

This example would have sufficed, reload from the menu,

Code: Select all

#Persistent

onexit l
onexit("f")
return

l:
	msgbox % a_exitreason
	exitapp
return

f(reason, code){
	msgbox % reason
}
which works as documented,
Any number of OnExit functions can be registered. If a label (subroutine) is also registered, the functions are called after the subroutine calls ExitApp. An OnExit function usually should not call ExitApp; if it does, the script terminates immediately.
Cheers.

Edit: made the example not reload automatically.
Last edited by Helgef on 17 Jan 2020, 23:54, edited 1 time in total.
1100++
Posts: 78
Joined: 10 Feb 2018, 19:05

Re: Wrong Exit Reason Displayed on Script Reload

16 Jan 2020, 10:19

For whatever reason, it doesn't work on the script I posted. It gives the reason "Exit" when reloaded.
Helgef
Posts: 4709
Joined: 17 Jul 2016, 01:02
Contact:

Re: Wrong Exit Reason Displayed on Script Reload

16 Jan 2020, 10:36

As documented (see quote above), the onexit funcs

Code: Select all

OnExit("ConfirmReload")
OnExit("ExitMsg")
will never show Reload due to the script executing

Code: Select all

OnExit ExitSub
If your problem persists, please post a minimal example which reproduces the problem.
Cheers.
joefiesta
Posts: 494
Joined: 24 Jan 2016, 13:54
Location: Pa., USA

Re: Wrong Exit Reason Displayed on Script Reload

17 Jan 2020, 15:38

Holy cow! What a complicated thing this is. I'm trying to figure it all out, so I revised Helgdef script to add more information in the msgboxes.

onexit l
onexit("f")
ct := 0
reload
return

l:
ct += 1
msgbox % "subroutine l: ct= " ct " a_exitreason= " a_exitreason
sleep 2000
exitapp
return

f(reason, code){
global ct
ct += 1
msgbox % "function f: ct= " ct " reason= " reason
sleep 2000
}


After I noticed that the code falls through (I think!!), I added the RETURN statement after the reload (as coded above).

1. Without the RETURN, the Label subroutine msgbox is displayed twice. But, when I add the RETIURN after RELOAD, I get what appear to be flashing msgbox(es). I don't understand why they just flash and disappear (since I also added the SLEEP statement after the msgboxes).
Can someone explain that?

2. Can someone explain why one would ever need to code both onexit Subroutines and Functions in the same script? (Yes, I should probably study the author's script but not sure I will get an answer doing so.)

3. why does my code box ruin the script's indentation? I choose the "C" icon to add the code.
Helgef
Posts: 4709
Joined: 17 Jul 2016, 01:02
Contact:

Re: Wrong Exit Reason Displayed on Script Reload

17 Jan 2020, 23:57

@joefiesta, I've changed the code to not reload automatically. Use code-tags instead, c-tags are for inline code.

Code: Select all

[code][/code] for code boxes
[c][/c] for inline code

Edit, @joefiesta, the documentation explicitly advice against using a label. The solution to the OP's problem is to use a function for each onexit routine.

Cheers
Helgef
Posts: 4709
Joined: 17 Jul 2016, 01:02
Contact:

Re: Wrong Exit Reason Displayed on Script Reload

06 Jul 2020, 03:15

1100++ wrote:FastStrRepeat()
I wouldn't recommend this approach,
wcsncat wrote: If copying takes place between strings that overlap, the behavior is undefined.
src

Cheers.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Rohwedder and 180 guests