如何在 WinTitle 参数中使用 AutoHotkey 实例变量?

How can AutoHotkey instance variables be used in WinTitle parameters?

假设我有一个函数可以使用进程的 HWND id:

获取进程的 window 标题
GetWindowTitle(hwnd) {
    WinGetTitle, title, ahk_id %hwnd%

    return title
}

到目前为止,还不错。它就像一个魅力。因此,假设我试图以这种方式将一些功能包装在 class 中:

class RunningProcess {
    hwnd := ""
    windowTitle := ""

    __New(hwnd) {
        this.hwnd := hwnd
        this.windowTitle := GetWindowTitle()
    }

    GetWindowTitle() {
        WinGetTitle, title, ahk_id %this.hwnd%

        return title
    }
}

上述代码加载失败并显示以下消息:

The following variable name contains an illegal character: "this.hwnd".

为了将实例变量 hwnd 用作 WinGetTitle 中的 WinTitle 参数,我尝试了几种替代方法,但无济于事。唯一对我有用的是使用局部变量获取 this.hwnd 的内容,然后将局部变量用作 WinTitle 参数,如下所示:

GetWindowTitle() {
    foo := this.hwnd
    WinGetTitle, title, ahk_id %foo%

    return title
}

但是,正如您可能猜到的那样,这并不理想,至少在我看来是这样。

有没有办法立即将 this.hwnd 用作 WinTitle 参数?

谢谢!

我将其称为传统表达式语法与现代表达式语法之间存在问题的经典案例。
虽然以这种方式看到它令人耳目一新,通常有问题的人都在写 2007 级 AHK,但很高兴看到你在写现代 AHK。

所以无论如何,忘记使用 %% 来引用变量。这就是传统的 AHK 方式。在现代表达式语句中,您只需键入要引用的变量的名称,例如,您使用 := operator are just fine that way, because it's using the modern expression syntax (= 进行赋值将是传统方式)

但是,几乎所有没有被更现代的功能取代的命令,仍然在每个参数上使用旧语法(除非文档中另有说明)。
因此,您将不得不设置参数来评估表达式,而不是期望使用遗留文本参数。为此,您可以使用一个 % 开始参数,然后使用 space.
所以你的 WinGetTitle 命令应该是这样的:

WinGetTitle, title, % "ahk_id " this.hwnd

ahk_id 周围的引号,因为这是您在表达式中指定字符串的方式,然后只需键入要连接到该字符串的变量。 concatenation operator . 可以像 % "ahk_id " . this.hwnd 一样在这里使用,但它完全是多余的,而且在我看来也很奇怪。

此外,您在初始化程序 __New 中对 GetWindowTitle() 函数的调用需要在其前面添加一个 this.
将实例变量初始化为 nothing 也是多余的。如果你愿意,你可以删除它。

成品:

MyCoolObject := new RunningProcess(WinExist("A"))
MsgBox, % "The handle of currently active window is: " MyCoolObject.hwnd "`nAnd its title is: " MyCoolObject.windowTitle

class RunningProcess
{
    __New(hwnd) 
    {
        this.hwnd := hwnd
        this.windowTitle := this.GetWindowTitle()
    }

    GetWindowTitle() 
    {
        WinGetTitle, title, % "ahk_id " this.hwnd
        return title
    }
}

要了解有关遗留语法与表达式语法的更多信息,请参阅文档中的示例页面: https://www.autohotkey.com/docs/Language.htm