首页 > 解决方案 > 为什么脚本不能正确地从 %SetWidth% 和 %SetHeight% 读取变量数据?

问题描述

当我用数字替换这些时,脚本可以正常工作。但为了简化事情,我想在脚本顶部定义几个变量(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

标签: autohotkey

解决方案


要访问函数中的全局变量,您需要

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在它们之前添加:

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

有关更多详细信息,请阅读局部变量和全局变量


推荐阅读