I think you mean "latter" rather than "former", and
If !(WinActive...) rather than
If (WinActive...).
Why would you ever use #If or #IfWinActive when you could use a normal If or If WinActive()? The answer is the same here.
Disabling a hotkey is not the same as sending it after it fires. The latter has side-effects, especially when you do it incorrectly. It is error-prone due to the difference in syntax and several modifiers that don't apply to Send. For example, your second code would send the literal text "$F9". If you
Send {F9}, it will have the side-effect of marking the event as generated by AutoHotkey, and it will send the up event immediately after the down event (not when you release the key).
Regarding code size, the first code has an unfair disadvantage because the condition is wrapped inside a function. This is necessary only to avoid repetition. Repetition of the expression is necessary because
Hotkey If is unable to create new expressions. But since the expression is just a call to a function with no parameters, it actually isn't necessary at all in this case. Instead of creating an expression with #If and referencing it with Hotkey, you can use the function directly:
Code: Select all
GuisAreActive(){
global hGui
Return (WinActive("ahk_id " GetNPPHwnd()) or WinActive("ahk_id " hGui))
}
SetHotkeys(){
f := Func("GuisAreActive") ; Separate assignment needed due to v1 limitations.
Hotkey, If, % f
Hotkey, F9, RunAHK
Hotkey, If
}
RunAHK(){
;Code
}
This is a complete working example in AutoHotkey v2-a099 (though
Hotkey "IfWinActive" would be more suitable in this case since
A_ScriptHwnd never changes):
Code: Select all
SetHotkeys()
ListHotkeys
SetHotkeys() {
Hotkey "If", () => WinActive("ahk_id " A_ScriptHwnd)
Hotkey "$F9", "RunAHK"
Hotkey "If"
}
RunAHK() {
MsgBox "Pressed F9 in the script's window."
}
However, if you use an anonymous function, you must pass a reference to the same anonymous function whenever you want to modify hotkeys originally created under that function. In other words, you can't just repeat the expression
() => whatever. If you need to modify the hotkeys (anywhere other than in SetHotkeys), you're better off with a separate function.
If you use a
closure (i.e. if the expression references a local variable or parameter of SetHotkeys), calling the SetHotkeys function again would create a totally new hotkey variant, since the object passed to
Hotkey "If" would be different each time. It is the same with bound functions in v1 and v2.
I presume the reason for not using IfWinActive and ahk_group in the original script is that the GUI and/or NPP HWND may change.