首页 > 解决方案 > 如何使用字符串作为参数

问题描述

自动热键非常新。我正在努力寻找如何使用字符串作为 ImageSearch 的变量。在我的代码中,我想只使用一个函数搜索 image1.png 和 image2.png,我通过参数发送图像的名称。

z:: 
    imageSearchFunction("image1.png")
    imageSearchFunction("image2.png")
return

imageSearchFunction(imagePath)
    ImageSearch, FoundX, FoundY, ScreenStartX, ScreenStartY, ScreenEndX, ScreenEndY, imagePath
    if (ErrorLevel = 2)
                MsgBox Error2
            else if (ErrorLevel = 1)
                MsgBox Error1
            else
                MsgBox Found the image

提前致谢

标签: autohotkey

解决方案


A lot wrong with this, lets start off with the code with which I guess was supposed to create a function.
To create a function you need to follow this syntax

function(param1, param2, ...)
{

}

Then your other problem is referring to variables in the legacy syntax.
So, you're using a command. Every command uses legacy syntax in every parameter (unless otherwise specified in the documentation).
When you just type in ScreenStartX, ScreenStartY, ScreenEndX, ScreenEndY, imagePath, it's interpreted as literal text. You're going to want to tell AHK to evaluate an expression on those parameters and then you can refer to the variable just by typing its name.
To do that, you start off the parameters with a % followed up by a whitespace.
% ScreenStartX, % ScreenStartY, % ScreenEndX, % ScreenEndY, % imagePath

Then you also have the problem of the variables ScreenStartX, ScreenStartY, ScreenEndX and ScreenEndY never even being defined. At least not in the code you provided and certainly not in the function's scope.
I'll just slap them some random values, since I have no idea what you're actually going for.

z:: 
    imageSearchFunction("image1.png")
    imageSearchFunction("image2.png")
return

imageSearchFunction(imagePath)
{
    ;should be made static, but I wont
    ;confuse you with that, since this more 
    ;than likely isnt the desired usage anyway
    ScreenStartX := 0
    ScreenStartY := 0
    ScreenEndX := 700
    ScreenEndY := 500
    
    ImageSearch, FoundX, FoundY, % ScreenStartX, % ScreenStartY, % ScreenEndX, % ScreenEndY, % imagePath
    if (ErrorLevel = 2)
        MsgBox, % "Error2"
    else if (ErrorLevel = 1)
        MsgBox, % "Error1"
    else
        MsgBox, % "Found the image at X: " FoundX ", Y: " FoundY
}

推荐阅读