Autohotkey - 我在使用 WinActive 和 Hotstring 编写代码时遇到了问题

Autohotkey - I had a problem writing code with WinActive and Hotstring

我需要代码来在记事本打开时启用 Hotstring 并在记事本关闭时禁用 Hotstring。所以我写了下面的代码,我发现这段代码有时会漏掉记事本打开的事件。我该如何解决?

while True
{
    begin:
    Sleep, 1
    ;Untitled - Notepad
    while not WinActive("Untitled - Notepad")
    {
        Sleep, 1
        if WinActive("Untitled - Notepad")
        {
            MsgBox WinActive
            HotString("::hello", "Hello World", On)
            
            goto, begin
    }
    HotString("::hello", "Hello World", Off)
    }
}

a::
ExitApp

#Directives 就是为了这个,更具体地说 #IfWinActive directive.
这是您的成品:

#IfWinActive, ahk_class Notepad
::hello::Hello World
#IfWinActive

ahk_class是为了方便。您可以阅读更多相关信息 here.
或者,例如 #IfWinActive, ahk_exe notepad.exe 也可以使用。
或者,当然,普通的 #IfWinActive, Untitled - Notepad 也可以,但只有当您编辑名为“Untitled”的文档时才有效。所以这就是为什么它不是一个好的方法。

AHKV1:

#If WinActive("ahk_class Notepad")
::hello::Hello World
#If

我推荐:

#HotIf WinActive("ahk_class Notepad")
::hello::Hello World
#HotIf