Monday, January 15, 2018

Sample code for Autohotkey to share (many times i forgot it, went not use long time) Find picture in background

;###########################################################################
;#############        1.    Find picture in background                         ####################
;###########################################################################
;needle="c:\picture.png" file location
;WinTitle = windows title screen that want to find
;L= number of loop check
;Cx,Cy = position click if not want to click picture

#Include D:\script\Gdip_all.ahk

bgfindpic(needle,WinTitle,L:=5,Cx:=0,Cy:=0)
{
needle=D:\script\%needle%.png
;msgbox %needle% %WinTitle%
loop
{
If !pToken := Gdip_Startup()
{
   MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
   ExitApp
}

; imagefile that you  want to find
;needle=%a_scriptdir%\needle.png  ;you need testimage needle.png

; title of window you want to search into
;WinTitle:="PSPad"  ;just example

hwnd:=WinExist(WinTitle) ; get the handle to the window
;msgbox %hwnd%  ;for debugging to see if there is a handle

bmpHaystack := Gdip_BitmapFromHWND(hwnd)  ;you need the handle of the window to search in
;Gdip_SaveBitmapToFile(bmpHaystack,"HWND.png") ; you can test to see what has been captured for debugging
bmpNeedle := Gdip_CreateBitmapFromFile(needle)
;Gdip_SaveBitmapToFile(bmpNeedle,"needle.png")

RET := Gdip_ImageSearch(bmpHaystack,bmpNeedle,LIST)
;Gdip_ImageSearch(pBitmapHaystack,pBitmapNeedle,ByRef OutputList="",OuterX1=0,OuterY1=0,OuterX2=0,OuterY2=0,Variation=0,Trans="",SearchDirection=1,Instances=1,LineDelim="`n",CoordDelim=",")
Gdip_DisposeImage(bmpHaystack)
Gdip_DisposeImage(bmpNeedle)
Gdip_Shutdown(pToken)
pos:=strsplit(list,",")
xp:=pos.1+5 ,yp:=pos.2+5
;tooltip  % xp "   "  yp
;ControlClick, x%xp% y%yp% , ahk_id %hwnd%,,,, Pos
;msgbox 1 %xp% %yp% %hwnd% %Wintitle% %needle%
if (xp>0 && yp>0)
{
if (cx<>0 && cy<>0)
{
xp:=cx
yp:=cy
}
ControlClick, x%xp% y%yp% , ahk_id %hwnd%,,left,, Pos
return 1
}
list=
sleep,3000
L:=L-1
if L=0
return 0
}
;msgbox "found"
}
return