为什么脚本不能正确地从 %SetWidth% 和 %SetHeight% 读取变量数据?

Why isn't the script reading the variable data from %SetWidth% and %SetHeight% Correctly?

当我用数字替换它们时,脚本运行正常。但为了简化事情,我想在脚本顶部定义几个变量(SetWidth 和 SetHeight)并在整个过程中根据需要调用它们。除了,出于某种原因,当我尝试调用它们时,它似乎无法正常工作。

#NoTrayIcon
#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

SetWidth = 1616
SetHeight = 939

Run, ".\full throttle remastered.bat"
Process, Wait, throttle.exe, 120
Process, Exist, throttle.exe
Throttle = %ErrorLevel%
if Throttle != 0
{
    Sleep, 2000
    CenterWindow("ahk_exe throttle.exe")
}
else
{
    MsgBox "Full Throttle Remastered could not be started"
}
return

; The following function centers the specified window on the screen if not already centered:
CenterWindow(WinTitle)
{
    WinGetPos,xx,yy, winx, winy, %WinTitle%
    x1 := xx + winx/2
    y1 := yy + winy/2
    loop 2
    { 
    y1 := yy + winy/2
        loop 2
        { 
            if ((A_ScreenWidth/2 = x1) && (A_ScreenHeight/2 = y1) && (winx = %SetWidth%) && (winy = %SetHeight%)) 
            {
                msgbox got em
            return
            }
            else
            y1 := y1 + 0.5
        }
    x1 := x1 + 0.5
    } 
    WinMove, ahk_exe throttle.exe,, 0, 0, %SetWidth%, %SetHeight%
    WinGetPos,,, winx, winy, %WinTitle%
    Sleep, 100
    WinMove, %WinTitle%,, (A_ScreenWidth/2)-(winx/2), (A_ScreenHeight/2)-(winy/2)
}
return

要在函数内访问全局变量,您需要

在函数内添加global

CenterWindow(WinTitle){
    global
    WinGetPos,xx,yy, winx, winy, %WinTitle%
    x1 := xx + winx/2
    y1 := yy + winy/2
    loop 2
    { 
    y1 := yy + winy/2
        loop 2
        { 
            if ((A_ScreenWidth/2 = x1) && (A_ScreenHeight/2 = y1) && (winx := SetWidth) && (winy = SetHeight)) 
            {
                msgbox got em
            return
            }
            else
            y1 := y1 + 0.5
        }
    x1 := x1 + 0.5
    }
    WinMove, %WinTitle%,, 0, 0, SetWidth, SetHeight
    WinGetPos,,, winx, winy, %WinTitle%
    Sleep, 100
    WinMove, %WinTitle%,, (A_ScreenWidth/2)-(winx/2), (A_ScreenHeight/2)-(winy/2)
}

或者通过在变量之前添加 global 将变量声明为函数外的超全局变量(在自动执行部分或 hotkey/hotstring/or 另一个函数内):

global SetWidth := "1616"
global SetHeight := "939"

有关详细信息,请阅读 Local and Global Variables