It can be hard to know where exactly a button is located on the screen, this is where PixelSearch comes in. The PixelSearch function of AutoIt allows to search a region of the screen for a given pixel color, you can then decide what to do if the color was found, which would often be clicking the coordinates where the color is found.
When multiple elements with the same color exists, its useful to only check the region where you know the unique color should show up. To check for a image, you will need to use other functions, these will be covered in a later Tutorial.
Performing a simple color search
The PixelSearch function works by feeding it with a color to check for, and a region to be checked. Its also possible to add a variation of the color, from 0-255, which is just a variation of the Red, Green, and Blue values.
Pixel searches are effected by the size of the area that you want to check, smaller areas are faster to scan than larger ones.
When the search is completed, we check @error to see if a color was found, nothing was found if it equals 1.
The below will check the region 0,0 (Start) - 100,200 (end) of the screen, the values are given from the Left Top of the screen.
$coord = PixelSearch(0, 0, 100, 200, 0xFF0000) If Not @error Then MsgBox(0, "X and Y are:", $coord & "," & $coord) EndIf
A two element array is returned if a color was found, containing the coordinates of the pixel it found. The search stops after finding a pixel matching the specified parameters.
Clicking the returned coordinates
Clicking the coordinates returned by the PixelSearch function, is fairly easy once a color is found.
$coord = PixelSearch(0, 0, 100, 200, 0xFF0000) If Not @error Then MouseClick("primary", $coord, $coord, 1, 0) EndIf
Looping the Pixel Search
You will often need to loop the pixel search, this is usually done when you want the program to wait for a click-able element to appear on the screen. It can sometimes help save CPU to make your script Sleep a few seconds, before running the check again.
$i = 0 While $i <= 10 $coord = PixelSearch(0, 0, 100, 200, 0xFF0000) If Not @error Then MouseClick("primary", $coord, $coord, 1, 0) EndIf ; Uncomment the below line to make the script click only 10 times, or until the hotkey is pressed. ; $i = $i + 1 ; Uncomment the below line to make the script pause between clicks, the value is in milliseconds ; Sleep(5000) WEnd