Leaderboard
Popular Content
Showing content with the highest reputation on 10/07/2022 in all areas
-
Version v3.5
11,683 downloads
ImageSearch UDF v3.5 - AutoIt Wrapper for ImageSearchDLL Advanced image search library for AutoIt with cache system and SIMD optimization. Overview ImageSearchDLL UDF is a high-performance image search library for AutoIt that enables you to find images on screen or within other images. Built with C++14 and optimized with SIMD instructions (AVX512/AVX2/SSE2), it provides fast and accurate image matching capabilities. Features High Performance: SIMD optimization (AVX512/AVX2/SSE2) for fast searching Multi-Monitor Support: Full support for multi-monitor setups with negative coordinates DPI Awareness: Thread-local DPI awareness without affecting AutoIt GUI Cache System: Persistent cache for 30-50% speed boost on repeated searches Image Scaling: Search for images at different scales (0.1x to 5.0x) Screen Capture: Direct screen capture with DPI-aware coordinates Mouse Automation: Precise mouse movement and clicking with multi-monitor support Requirements AutoIt: Version 3.3.16.1 or higher Windows: XP SP3 to Windows 11 Architecture: x86 or x64 (automatic detection) DLL: ImageSearchDLL v3.5 (included) Installation Download the UDF package Place ImageSearchDLL_UDF.au3 in your script directory Ensure the appropriate DLL is in the same directory: ImageSearchDLL_x64.dll for 64-bit AutoIt ImageSearchDLL_x86.dll for 32-bit AutoIt Not required in embedded version! (But need to install Visual C++ Redistributable 2015-2022) Include the UDF in your script: #include "ImageSearchDLL_UDF.au3" Quick Start Basic Image Search #include "ImageSearchDLL_UDF.au3" ; Search for a button on screen Local $aResult = _ImageSearch("button.png") If $aResult[0] > 0 Then ConsoleWrite("Found at: " & $aResult[1][0] & ", " & $aResult[1][1] & @CRLF) MouseClick("left", $aResult[1][0], $aResult[1][1]) Else ConsoleWrite("Image not found" & @CRLF) EndIf Wait for Image and Click ; Wait up to 5 seconds for button to appear, then click it If _ImageSearch_WaitClick(5000, "button.png") Then MsgBox(0, "Success", "Button clicked!") Else MsgBox(0, "Failed", "Button not found within 5 seconds") EndIf Screen Capture ; Capture a region and save as PNG _ImageSearch_ScreenCapture_SaveImage(@ScriptDir & "\screenshot.png", 100, 100, 600, 400) ; Capture full screen _ImageSearch_ScreenCapture_SaveImage(@ScriptDir & "\fullscreen.png") API Reference Startup & Configuration _ImageSearch_Startup() Initializes the ImageSearch library by loading the appropriate DLL. Returns: Success: 1 (DLL loaded successfully) Failure: 0 and sets @error Remarks: Must be called before using any search functions Automatically called on script start DLL v3.5+ uses thread-local DPI awareness and won't affect AutoIt GUI _ImageSearch_Shutdown() Closes the DLL and cleans up resources. _ImageSearch_SetDllPath($sPath) Sets a custom DLL path (must be called before _ImageSearch_Startup). Parameters: $sPath - Full path to the DLL file Returns: Success: 1 Failure: 0 (file not found) Core Search Functions _ImageSearch($sImagePath [, $iLeft, $iTop, $iRight, $iBottom [, $iScreen [, $iTolerance [, $iResults [, $iCenterPOS [, $fMinScale [, $fMaxScale [, $fScaleStep [, $iReturnDebug [, $iUseCache]]]]]]]]) Searches for an image within a specified screen area. Parameters: $sImagePath - Image file path(s), multiple separated by "|" $iLeft, $iTop, $iRight, $iBottom - Search region (0 = entire screen) $iScreen - Monitor index (-1 = virtual screen, 0 = primary, 1+ = specific monitor) $iTolerance - Color tolerance 0-255 (default: 10) $iResults - Max results 1-1024 (default: 1) $iCenterPOS - Return center (1) or top-left (0) coordinates (default: 1) $fMinScale, $fMaxScale - Scale range 0.1-5.0 (default: 1.0) $fScaleStep - Scale step (default: 0.1) $iReturnDebug - Debug mode (default: 0) $iUseCache - Enable cache (default: 1) Returns: Success: Array of found positions [count][X, Y, Width, Height] Failure: Empty array with @error set Example: ; Search for multiple images with scaling Local $aResult = _ImageSearch("icon1.png|icon2.png", 0, 0, 800, 600, -1, 10, 5, 1, 0.8, 1.2, 0.1) If $aResult[0] > 0 Then For $i = 1 To $aResult[0] ConsoleWrite("Match " & $i & " at: " & $aResult[$i][0] & ", " & $aResult[$i][1] & @CRLF) Next EndIf _ImageSearch_InImage($sSourceImage, $sTargetImage [, $iTolerance [, $iResults [, $iCenterPOS [, $fMinScale [, $fMaxScale [, $fScaleStep [, $iReturnDebug [, $iUseCache]]]]]]]]) Searches for a target image within a source image (file-to-file search). Parameters: $sSourceImage - Path to source image file $sTargetImage - Path to target image file(s), multiple separated by "|" Other parameters same as _ImageSearch Returns: Same as _ImageSearch Remarks: Useful for pre-processing images or testing without screen capture Example: $aResult = _ImageSearch_InImage("screenshot.png", "button.png", 20) _ImageSearch_hBitmap($hBitmapSource, $hBitmapTarget [, $iTolerance [, $iLeft [, $iTop [, $iRight [, $iBottom [, $iResults [, $iCenterPOS [, $fMinScale [, $fMaxScale [, $fScaleStep [, $iReturnDebug [, $iUseCache]]]]]]]]]]]]) Searches for a target bitmap within a source bitmap (memory-to-memory search). Parameters: $hBitmapSource - Handle to source bitmap (HBITMAP) $hBitmapTarget - Handle to target bitmap (HBITMAP) Other parameters same as _ImageSearch Returns: Same as _ImageSearch Remarks: Fastest method for repeated searches (no disk I/O) Bitmaps must be created with GDI/GDI+ functions Screen Capture Functions _ImageSearch_CaptureScreen([$iLeft, $iTop, $iRight, $iBottom [, $iScreen]]) Capture screen region and return as HBITMAP handle. Parameters: $iLeft, $iTop, $iRight, $iBottom - Capture region (default: 0 = full screen) $iScreen - Monitor index (default: -1 = virtual screen) Returns: Success: HBITMAP handle (must DeleteObject when done) Failure: 0 and sets @error Example: $hBitmap = _ImageSearch_CaptureScreen(0, 0, 800, 600) ; ... use $hBitmap ... _WinAPI_DeleteObject($hBitmap) _ImageSearch_ScreenCapture_SaveImage($sImageFile [, $iLeft [, $iTop [, $iRight [, $iBottom [, $iScreen]]]]]) Captures a screen region and saves it directly to an image file in one call. Parameters: $sImageFile - Output file path (extension determines format: .bmp, .png, .jpg/.jpeg) $iLeft, $iTop, $iRight, $iBottom - Capture region (default: 0 = full screen) $iScreen - Monitor index (default: 0 = primary screen) Returns: Success: True (1) Failure: False (0) and sets @error Remarks: Automatically detects format from file extension ~2x faster than separate capture + save operations JPEG quality is fixed at 100% (highest quality) Uses DPI-aware capture (accurate on all DPI scales) Example: ; Capture full primary screen to PNG _ImageSearch_ScreenCapture_SaveImage(@ScriptDir & "\screenshot.png") ; Capture region on monitor 2 to JPEG _ImageSearch_ScreenCapture_SaveImage(@ScriptDir & "\region.jpg", 100, 100, 600, 400, 2) _ImageSearch_hBitmapLoad($sImageFile [, $iAlpha [, $iRed [, $iGreen [, $iBlue]]]]) Load image file and convert to HBITMAP handle. Parameters: $sImageFile - Path to image file $iAlpha, $iRed, $iGreen, $iBlue - Background color components 0-255 (default: 0 = transparent) Returns: Success: HBITMAP handle (must DeleteObject when done) Failure: 0 and sets @error Example: $hBitmap = _ImageSearch_hBitmapLoad("image.png", 255, 255, 255, 255) ; White background ; ... use $hBitmap ... _WinAPI_DeleteObject($hBitmap) Mouse Functions _ImageSearch_MouseMove($iX, $iY [, $iSpeed [, $iScreen]]) Moves mouse cursor to coordinates (supports negative coordinates on multi-monitor). Parameters: $iX, $iY - Target coordinates (-1 = keep current position) $iSpeed - Speed 0-100 (0=instant, default: 0) $iScreen - Monitor index (default: -1 = virtual screen) Returns: 1 on success, 0 on failure _ImageSearch_MouseClick([$sButton [, $iX [, $iY [, $iClicks [, $iSpeed [, $iScreen]]]]]]) Clicks mouse at coordinates (screen or current position). Parameters: $sButton - Button: "left", "right", "middle" (default: "left") $iX, $iY - Coordinates (-1 = current position) $iClicks - Number of clicks (default: 1) $iSpeed - Speed 0-100 (0=instant, default: 0) $iScreen - Monitor index (default: -1 = virtual screen) Returns: 1 on success, 0 on failure _ImageSearch_MouseClickWin($sTitle, $sText, $iX, $iY [, $sButton [, $iClicks [, $iSpeed]]]) Clicks mouse in a window. Parameters: $sTitle - Window title/class/handle $sText - Window text $iX, $iY - Relative coordinates in window $sButton - Button (default: "left") $iClicks - Number of clicks (default: 1) $iSpeed - Speed 0-100 (default: 0) Returns: 1 on success, 0 on failure Wait & Click Functions _ImageSearch_Wait($iTimeout, $sImagePath [, $iLeft [, $iTop [, $iRight [, $iBottom [, $iScreen [, $iTolerance [, $iResults [, $iCenterPOS [, $fMinScale [, $fMaxScale [, $fScaleStep [, $iReturnDebug [, $iUseCache [, $iMaxAttempts]]]]]]]]]]]]]) Waits for an image to appear on screen with timeout and optional max attempts limit. Parameters: $iTimeout - Timeout in milliseconds (0 = wait forever) $sImagePath - Image file path(s), multiple separated by "|" $iMaxAttempts - Max number of search attempts (0 = unlimited, default: 0) Other parameters same as _ImageSearch Returns: Success: 2D Array (same as _ImageSearch) Timeout: Empty array with [0][0] = 0 Example: ; Wait 5 seconds for button (unlimited attempts) $aResult = _ImageSearch_Wait(5000, "button.png") If $aResult[0] > 0 Then MouseClick("left", $aResult[1][0], $aResult[1][1]) Else MsgBox(0, "Timeout", "Button not found") EndIf _ImageSearch_WaitClick($iTimeout, $sImagePath [, $sButton [, $iClicks [, $iLeft [, $iTop [, $iRight [, $iBottom [, $iScreen [, $iTolerance [, $iResults [, $iCenterPOS [, $fMinScale [, $fMaxScale [, $fScaleStep [, $iReturnDebug [, $iUseCache]]]]]]]]]]]]]) Waits for an image and clicks it when found. Parameters: $iTimeout - Timeout in milliseconds (0 = wait forever) $sImagePath - Image file path(s) $sButton - Mouse button: "left", "right", "middle" (default: "left") $iClicks - Number of clicks (default: 1) Other parameters same as _ImageSearch Returns: Success: 1 (image found and clicked) Timeout: 0 (image not found) Monitor Functions _ImageSearch_Monitor_GetList() Gets a list of all connected display monitors and their properties. Returns: Success: The number of monitors found. @extended contains a detailed log. Failure: 0 and sets @error Remarks: Populates the global $g_aMonitorList Called automatically by _ImageSearch_Startup _ImageSearch_Monitor_ToVirtual($iMonitor, $iX, $iY) Converts local monitor coordinates to virtual screen coordinates. Parameters: $iMonitor - The 1-based index of the monitor $iX, $iY - Coordinates relative to the monitor's top-left corner Returns: Success: A 2-element array [$vX, $vY] containing virtual screen coordinates Failure: 0 and sets @error _ImageSearch_Monitor_FromVirtual($iMonitor, $iX, $iY) Converts virtual screen coordinates to local monitor coordinates. Parameters: $iMonitor - The 1-based index of the monitor $iX, $iY - Virtual screen coordinates Returns: Success: A 2-element array [$lX, $lY] containing local monitor coordinates Failure: 0 and sets @error _ImageSearch_Monitor_Current() Detects which monitor contains the current mouse cursor position. Returns: Success: Monitor index (1-based) where the cursor is located Failure: 0 and sets @error _ImageSearch_Monitor_GetAtPosition([$iX [, $iY]]) Returns detailed information string about the monitor at specified position. Parameters: $iX, $iY - Coordinates (default: -1 = use mouse cursor position) Returns: Success: String describing the monitor (e.g., "Monitor 2: 1920x1080 (Primary)") Failure: Error message string Window Coordinate Functions _ImageSearch_Window_ToScreen($hWnd, $iX, $iY [, $bClientArea]) Converts window-relative coordinates to screen (virtual desktop) coordinates. Parameters: $hWnd - Window handle or title $iX, $iY - Coordinates relative to window $bClientArea - True = relative to client area, False = relative to window (default: True) Returns: Success: A 2-element array [$screenX, $screenY] containing screen coordinates Failure: 0 and sets @error _ImageSearch_Window_FromScreen($hWnd, $iScreenX, $iScreenY [, $bClientArea]) Converts screen (virtual desktop) coordinates to window-relative coordinates. Parameters: $hWnd - Window handle or title $iScreenX, $iScreenY - Screen coordinates $bClientArea - True = relative to client area, False = relative to window (default: True) Returns: Success: A 2-element array [$winX, $winY] containing window-relative coordinates Failure: 0 and sets @error Cache & Info Functions _ImageSearch_WarmUpCache($sImagePaths [, $bEnableCache]) Pre-loads images into cache for faster subsequent searches. Parameters: $sImagePaths - Pipe-separated list of images to preload $bEnableCache - Enable persistent cache (default: True) Returns: Success: Number of images cached Failure: 0 Example: _ImageSearch_WarmUpCache("btn1.png|btn2.png|icon.png") _ImageSearch_ClearCache() Clears the internal bitmap and location cache. Remarks: Useful for freeing memory or forcing re-scan after image updates Clears both in-memory cache and persistent disk cache _ImageSearch_GetDllInfo([$bForceRefresh]) Gets comprehensive DLL information in INI format. Parameters: $bForceRefresh - Force refresh of cached info (default: True) Returns: Multi-line string in INI format with sections: [DLL] - DLL name, version, architecture, author [OS] - OS name, version, build, platform [CPU] - Threads, SSE2, AVX2, AVX512 support [SCREEN] - Virtual screen, scale, monitors with individual resolutions [CACHE] - Location cache, bitmap cache, pool size _ImageSearch_GetInfo() Gets formatted DLL and system information for display. Returns: Formatted string with DLL info, cache status, and screen information _ImageSearch_GetDllValue($sSection, $sKey) Quick accessor to read any value from cached DLL Info. Parameters: $sSection - Section name (DLL, OS, CPU, SCREEN, CACHE) $sKey - Key name Returns: Value string or "" if not found Example: $sVersion = _ImageSearch_GetDllValue("DLL", "Version") $sOSName = _ImageSearch_GetDllValue("OS", "Name") $iThreads = _ImageSearch_GetDllValue("CPU", "Threads") _ImageSearch_GetLastResult() Gets the raw DLL return string from the last search. Returns: Raw result string (e.g., "{2}[100|200|32|32,150|250|32|32]") Remarks: Useful for debugging or custom parsing _ImageSearch_GetScale([$iScreen]) Gets the DPI scale factor for a specific monitor as a decimal number. Parameters: $iScreen - Monitor index (0 = Primary, 1+ = specific monitor number) Returns: Scale factor as number (e.g., 1.0, 1.25, 1.5) or 0 if not found Example: $fScale = _ImageSearch_GetScale(0) ; Get primary monitor scale (e.g., 1.25) $fScale = _ImageSearch_GetScale(2) ; Get monitor 2 scale Examples Advanced Search with Multiple Images and Scaling #include "ImageSearchDLL_UDF.au3" ; Search for multiple UI elements with different scales Local $sImages = "button_ok.png|button_cancel.png|icon_settings.png" Local $aResult = _ImageSearch($sImages, 0, 0, 1920, 1080, -1, 15, 10, 1, 0.8, 1.3, 0.1, 0, 1) If $aResult[0] > 0 Then ConsoleWrite("Found " & $aResult[0] & " matches:" & @CRLF) For $i = 1 To $aResult[0] ConsoleWrite(" Match " & $i & ": X=" & $aResult[$i][0] & ", Y=" & $aResult[$i][1] & ", W=" & $aResult[$i][2] & ", H=" & $aResult[$i][3] & @CRLF) Next Else ConsoleWrite("No matches found" & @CRLF) EndIf Multi-Monitor Screen Capture #include "ImageSearchDLL_UDF.au3" ; Get monitor information _ImageSearch_Monitor_GetList() ConsoleWrite("Detected " & $g_aMonitorList[0][0] & " monitors" & @CRLF) ; Capture each monitor separately For $i = 1 To $g_aMonitorList[0][0] Local $sFile = @ScriptDir & "\monitor_" & $i & ".png" _ImageSearch_ScreenCapture_SaveImage($sFile, 0, 0, 0, 0, $i) ConsoleWrite("Captured monitor " & $i & " to: " & $sFile & @CRLF) Next ; Capture entire virtual desktop _ImageSearch_ScreenCapture_SaveImage(@ScriptDir & "\virtual_desktop.png", 0, 0, 0, 0, -1) Automated UI Testing #include "ImageSearchDLL_UDF.au3" ; Pre-load images for better performance _ImageSearch_WarmUpCache("login_button.png|username_field.png|password_field.png") ; Wait for login screen and interact If _ImageSearch_WaitClick(10000, "login_button.png") Then ConsoleWrite("Login button clicked" & @CRLF) ; Find username field and click Local $aUsername = _ImageSearch_Wait(5000, "username_field.png") If $aUsername[0] > 0 Then MouseClick("left", $aUsername[1][0], $aUsername[1][1]) Send("myusername") ; Find password field and click Local $aPassword = _ImageSearch_Wait(5000, "password_field.png") If $aPassword[0] > 0 Then MouseClick("left", $aPassword[1][0], $aPassword[1][1]) Send("mypassword") Send("{ENTER}") EndIf EndIf Else MsgBox(0, "Error", "Login screen not found within 10 seconds") EndIf Error Codes Code Constant Description -1 $IMGSE_INVALID_PATH Invalid file path -2 $IMGSE_FAILED_TO_LOAD_IMAGE Failed to load image -3 $IMGSE_FAILED_TO_GET_SCREEN_DC Failed to get screen device context -4 $IMGSE_INVALID_SEARCH_REGION Invalid search region -5 $IMGSE_INVALID_PARAMETERS Invalid parameters -6 $IMGSE_INVALID_SOURCE_BITMAP Invalid source bitmap -7 $IMGSE_INVALID_TARGET_BITMAP Invalid target bitmap -9 $IMGSE_RESULT_TOO_LARGE Result too large -10 $IMGSE_INVALID_MONITOR Invalid monitor Performance Tips Use Cache: Enable cache for repeated searches to get 30-50% speed boost Pre-load Images: Use _ImageSearch_WarmUpCache() during initialization Limit Search Area: Specify search regions instead of full screen when possible Optimize Tolerance: Use appropriate tolerance values (5-15 for most cases) Use Appropriate Scale Range: Limit scale range to what you actually need Monitor Selection: Use specific monitor index for faster searches on multi-monitor setups Image Format: BMP files load faster than PNG/JPG but are larger Memory Management: Always call _WinAPI_DeleteObject() for HBITMAP handles Changelog Version 3.5 Added thread-local DPI awareness (no GUI resize issues) Enhanced multi-monitor support with individual monitor scales Improved cache system with persistent disk cache Added _ImageSearch_ScreenCapture_SaveImage() for direct file saving Performance optimizations with SIMD instructions Better error handling and debugging information License This project is licensed under the MIT License - see the LICENSE file for details. Author Dao Van Trong - TRONG.PRO Thank you for using ImageSearch UDF! 🚀 ☕ Support My Work Enjoy my work? Buy me a 🍻 or tip via ❤️ PayPal Happy Automating! 🚀 ___________________________1 point -
Hi @robertocm I tried to "patch" that list a bit brutally to get it to work (at least for the "First name" field only). From some previous random experiments I did long ago, I noticed a few facts: to capture the events triggered by an object, it is convenient to use the reference to that specific object in the ObjEvent() function rather than referring generically to the "Document" object (although perhaps (some) events manage to reach the "Document" via bubbling) . Also, a quirk that I don't know why this happens, is that if get a reference to an html object that you want to manage, through the usual methods like .getElementById for example, well, ObjEvent() might not work. After several attempts, I then found that using the "ploy" I included in my _WebBrowser_JS_ElementGetRef() function, the returned reference will make the ObjEvent() function work "miraculously". I have therefore also used that function in this patch. I don't have much experience on how, when and which events can be used among that multitude of events described here: https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/hh801967(v=vs.85) but it would be interesting to try them all and catalog them by extracting the ones that will actually work in AutoIt .... here the patched list. p.s. (to simplify I also removed the <form> ... </form> tags from the HTML) #include <GUIConstantsEx.au3> #include <MsgBoxConstants.au3> Global $g_idGUIEdit Example() Exit ; End of our Demo. Func Example() Local $hGUIMain = GUICreate("Event Test", 1000, 600) $g_idGUIEdit = GUICtrlCreateEdit("", 5, 405, 990, 175) ; GUICtrlSetBkColor(-1, 0x000000) ; GUICtrlSetColor(-1, 0x00FF00) GUICtrlSetFont(-1, 9, 400, -1, 'Courier New') GUICtrlCreateLabel("Below are some Browser events 'captured' from the above web page by AutoIt", 5, 385, 990, 20) Local $idGUIExit = GUICtrlCreateButton(" Close and exit", 5, 580, 990, 15) GUISetState() ;Show GUI ; We prepare the Internet Explorer as our test subject Global $oIE = ObjCreate("Shell.Explorer.2") $hIE = GUICtrlCreateObj($oIE, 5, 5, 990, 380) ; <- insert $oIE in the AutoIt GUI ; Here we load an example Web page just to have something viewed in the browser ;$oIE.navigate('http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/onmousemoveEX.htm') ;>>>> ;These lines from: Chimp, Jan 2017 (edited) ;Who is Who ? (a little drag&drop game) ;https://www.autoitscript.com/forum/topic/186422-who-is-who-a-little-dragdrop-game/ ;Global $oIE = ObjCreate("Shell.Explorer.2") ; Create a BrowserControl ;Local $hGUI = GUICreate("", 660, 600, 30, 30) ;GUICtrlCreateObj($oIE, 0, 0, 660, 600) ; Place BrowserControl on the GUI ;GUISetState() ;Show GUI $oIE.navigate('about:blank') ; file:///' & @ScriptDir & '\WhoIsWho.html') While Not String($oIE.readyState) = 'complete' ; wait for about:blank Sleep(100) WEnd ; this waits till the document is ready to be used (portion of code from IE.au3) While Not (String($oIE.readyState) = "complete" Or $oIE.readyState = 4) Sleep(100) WEnd While Not (String($oIE.document.readyState) = "complete" Or $oIE.document.readyState = 4) Sleep(100) WEnd $oIE.document.Write(_GetHTML()) ; inject lising directly to the HTML document: $oIE.document.close() ; close the write stream $oIE.document.execCommand("Refresh") While Not String($oIE.readyState) = 'complete' ; wait for readyState after a refresh Sleep(100) WEnd $oDocument = $oIE.document ;>>>> ;~ Sleep(1000) ; Give it some time to load the web page ;~ Do ; wait for document ;~ Sleep(250) ;~ $oDocument = $oIE.document ;~ Until IsObj($oDocument) ; + Scripting Object Interfaces ; | --------------------------- ; | https://msdn.microsoft.com/en-us/library/hh801967(v=vs.85).aspx ; | ; +--> HTMLDocumentEvents2 interface (catch OnClick, OnMouseOver, .... etc ; ----------------------------- ; https://msdn.microsoft.com/en-us/library/aa769764(v=vs.85).aspx ; Global $oEventObject = ObjEvent($oDocument, "IEEvent2_", "HTMLDocumentEvents2") If @error Then MsgBox($MB_OK, "AutoIt COM Test", _ "ObjEvent: Can't use event interface 'HTMLDocumentEvents2'. Error code: " & Hex(@error, 8)) Exit EndIf ; ============================================================== Local $MyRef = $oIE.document.getElementById('firstname') ; MsgBox(0,0,VarGetType($MyRef)) Local $hMyObj = _WebBrowser_JS_ElementGetRef($oIE, $MyRef) ; MsgBox(0,0, VarGetType($hMyObj) & @CRLF & $hMyObj) ; https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa753143(v=vs.85) Global $oEventObjectInput = ObjEvent($hMyObj, "IEEvent_Input_", "HTMLInputTextElementEvents2") If @error Then MsgBox($MB_OK, "AutoIt COM Test", _ "ObjEvent: Can't use event interface 'HTMLInputTextElementEvents2'. Error code: " & Hex(@error, 8)) Exit EndIf ; ============================================================== ; GUISwitch($hGUIMain) ; Switch back to our GUI in case IE stole the focus ; Waiting for user to close the GUI. Local $iMsg While 1 $iMsg = GUIGetMsg() If $iMsg = $GUI_EVENT_CLOSE Or $iMsg = $idGUIExit Then ExitLoop WEnd $oEventObject.Stop ; Tell IE we don't want to receive events. $oEventObject = 0 ; Kill the Event Object $oIE = 0 ; Remove IE from memory (not really necessary). GUIDelete() ; Remove GUI EndFunc ;==>Example ; A few Internet Explorer Event Functions ; ( reference to the Event Obj interface: ) ; ( https://msdn.microsoft.com/en-us/library/aa703876(v=vs.85).aspx ) ; Volatile Func IEEvent2_onClick($oEvent) ConsolePrint("mouse click: " & $oEvent.clientX & ',' & $oEvent.clientY & ' on ' & $oEvent.srcElement.NodeName & ' id: ' & $oEvent.srcElement.id) If $oEvent.srcElement.NodeName = "INPUT" Then If $oEvent.srcElement.type = "radio" Or $oEvent.srcElement.type = "checkbox" Then If $oEvent.srcElement.checked = True Then ConsolePrint("name: " & $oEvent.srcElement.name & " id " & $oEvent.srcElement.id & " True") Else ConsolePrint("name: " & $oEvent.srcElement.name & " id " & $oEvent.srcElement.id & " False") EndIf EndIf EndIf EndFunc ;==>IEEvent2_onClick Volatile Func IEEvent2_onDblClick($oEvent) ConsolePrint("mouse DoubleClick: @" & $oEvent.clientX & ',' & $oEvent.clientY) EndFunc ;==>IEEvent2_onDblClick ;~ Volatile Func IEEvent2_onMouseMove($oEvent) ;~ ConsolePrint("mouse moved to:" & @TAB & "Xpos = " & $oEvent.clientX & @TAB & "Ypos = " & $oEvent.clientY) ;~ EndFunc ;==>IEEvent2_onMouseMove ; =================================== Volatile Func IEEvent_Input_onkeydown($oEvent) ; onChange($oEvent) ConsolePrint("KeyCode: " & $oEvent.keyCode) EndFunc ;==>IEEvent_Input_onkeydown Volatile Func IEEvent_Input_onchange($oEvent) ; Fires when you exit from the input and ONLY IF YOU HAVE CHANGED IT'S CONTENT ; ---- ------------------------------------- ConsolePrint('Input content in "First name" field has changed') EndFunc ;==>IEEvent_Input_onchange ; =================================== Func ConsolePrint($sMsg) Local Const $iMaxLines = 9 ; keep last 9 log lines only $sMsg = @HOUR & ':' & @MIN & ':' & @SEC & ':' & @MSEC & @TAB & $sMsg & @CRLF $sMsg = StringReplace(GUICtrlRead($g_idGUIEdit) & $sMsg, @CR, @CR) If @extended > $iMaxLines Then ; more than $iMaxLines $sMsg = StringMid($sMsg, StringInStr($sMsg, @CR, 0, -1 * $iMaxLines) + 2) EndIf GUICtrlSetData($g_idGUIEdit, $sMsg) EndFunc ;==>ConsolePrint Func _GetHTML() ;form html code from: Marc Clifton, 16 Feb 2013, https://www.codeproject.com/Articles/547451/WebBrowser-Element-Events-and-Values Local $sHTML = _ "<!DOCTYPE HTML>" & @CRLF & _ "<html>" & @CRLF & _ "<head>" & @CRLF & _ "<meta http-equiv=""X-UA-Compatible"" content=""IE=edge"" />" & @CRLF & _ "<title>Test</title>" & @CRLF & _ "</head>" & @CRLF & _ "<body>" & @CRLF & _ '<button type="button" id="btnMenu">=</button>' & @CRLF & _ '<button type="button" id="btnClose">X</button>' & @CRLF & _ '' & _ ; '<form>' & @CRLF & _ ; 'First name: <input id="firstname" type="text" name="firstname"/><br/>' & @CRLF & _ 'Last name: <input id="lastname" type="text" name="lastname"/><br/>' & @CRLF & _ 'Password: <input id="password" type="password" name="pwd"/><br><br/>' & @CRLF & _ '<input type="radio" id="male" name="sex" value="male"/>Male<br/>' & @CRLF & _ '<input type="radio" id="female" name="sex" value="female"/>Female<br/><br/>' & @CRLF & _ '<input type="checkbox" id="bike" name="vehicle" value="Bike"/>I have a bike<br/>' & @CRLF & _ '<input type="checkbox" id="car" name="vehicle" value="Car"/>I have a car <br/><br/>' & @CRLF & _ '<input type="button" id="ok" value="OK"/><br/>' & @CRLF & _ '<input type="button" id="cancel" value="Cancel"/><br/><br/>' & @CRLF & _ '' & _ ; '</form>' & @CRLF & _ ; "</body>" & @CRLF & _ "</html>" Return $sHTML EndFunc ;==>_GetHTML ; see here: https://www.autoitscript.com/forum/topic/200338-browsercontrol-companion Func _WebBrowser_JS_ElementGetRef(ByRef $oIE_Server, $oElement) Local $oWindow = $oIE_Server.document.parentwindow ; .JSglobal Local $oElementByIdReference If $oElement.Id = '' Then $oElement.setAttribute('Id', 'DummyId') ; we need an ID (a temporary ID) $oElementByIdReference = Execute('$oWindow.' & $oElement.getAttribute('Id')) ; get element's reference by Id $oElement.setAttribute('Id', '') ; remove the temporary ID (we leave things as we found them) Else $oElementByIdReference = Execute('$oWindow.' & $oElement.getAttribute('Id')) EndIf Return $oElementByIdReference EndFunc ;==>_WebBrowser_JS_ElementGetRef1 point
-
Changing all coordinates in a long script to work on different monitor?
Musashi reacted to pixelsearch for a topic
To do that, you could modify directly a function in imagesearch udf (or in a copy of it, leaving the original untouched) and apply the _WinAPI_ScreenToClient function directly in imagesearch udf. This will modify the coords returned from the function, changing them automatically from screen coords to client coords, I succeeded to do it by adding : * 1 line in the calling script * modifying a function in imagesearch udf I never used imagesearch until now but it was an interesting challenge. The problem is that we're not using the same imagesearch udf. Looking at your code above, you're probably using the one found in this link (dll's from 2010 which crash my computer) and call the function like this : $T22 = _ImageSearch("Images\T22.png", 0, $x3, $y3, 40) ; 0 = return top & left coord, tolerance 40 My successful test was done on a more recent ImageSearch Udf found in this link, from user VIP Trong, which calls the function like that : Local $aRet = _ImageSearch($sImage_Name, 40, False) ; tolerance 40 , False = return top & left coord ; Array result : $aRet[0] = 1 (success, image found) => $aRet[1] = top coord, $aRet[2] = left coord Anyway, no matter the ImageSearch UDF used, the logic should be same in both ImageSearch UDF Calling script : #include <MsgBoxConstants.au3> #include "Copy of _ImageSearch_UDF.au3" Local $sImage_Name = "notepad-logo.bmp" Local $hGUI = GUICreate("Test with VIP's _ImageSearch", 800, 600, 100, 100) ; GUI left & top at 100, 100 Local $idPic = GUICtrlCreatePic($sImage_Name, 20, 40, 18, 25) ; 18 x 25 = original pic size GUISetState(@SW_SHOW) ;============================== $g_hGUI_ForClientCoords = $hGUI ; force _ImageSearch to return client cooords (this Global variable = 0 in Copy of _ImageSearch_UDF.au3) ;============================== Local $aRet = _ImageSearch($sImage_Name, 40, False) If $aRet[0] = 1 Then MsgBox($MB_TOPMOST, 'Success', 'Image found:' & " X=" & $aRet[1] & " Y=" & $aRet[2] & @CRLF & $sImage_Name) Else MsgBox($MB_TOPMOST, 'Failed', 'Image not found') EndIf GUIDelete($hGUI) VIP's ImageSearch UDF (the modified part) : ; 2 lines added at top of the UDF #include <WinAPIConv.au3> ; for _WinAPI_ScreenToClient Global $g_hGUI_ForClientCoords = 0 ; change it in calling script to return client coords ... Func _ImageSearch($_ImagePath, $_Tolerance = 0, $_CenterPos = True) ; Commented 1 original line from VIP Trong ; Return _ImageSearch_Area($_ImagePath, 0, 0, @DesktopWidth, @DesktopHeight, $_Tolerance, $_CenterPos) ; Added all the following lines Local $aRet = _ImageSearch_Area($_ImagePath, 0, 0, @DesktopWidth, @DesktopHeight, $_Tolerance, $_CenterPos) If $aRet[0] = 1 And $g_hGUI_ForClientCoords Then ; $aRet[0] = 1 means success Local $tPoint = DllStructCreate("int X;int Y") DllStructSetData($tPoint, "X", $aRet[1]) DllStructSetData($tPoint, "Y", $aRet[2]) _WinAPI_ScreenToClient($g_hGUI_ForClientCoords, $tPoint) $aRet[1] = $tPoint.X $aRet[2] = $tPoint.Y EndIf Return $aRet EndFunc ;==>_ImageSearch ; * -----:| Dao Van Trong - TRONG.LIVE So, as soon as this line in the calling script is active... $g_hGUI_ForClientCoords = $hGUI ...then the same client coords will always be returned, no matter the GUI is displayed at 100, 100 or 200, 200 . If you comment that line, then screen coords will be returned. Hope it helps1 point -
https://github.com/robertluwang/scite-setting/blob/master/scite-dark-theme.md1 point
-
Problem with GUICtrlRead in second GUI
abberration reacted to JB72 for a topic
Yes this works fine 🙂 I work with the ISN AutoIT Studio and i use the Forms-Studio 2 Editor. So in the "main".au3 ist the form inclueded, at the top of the script, but this does not work in this case. The include of the created gui must be in the function now. Func _CreateRadios() #include "Forms\ChooseScript.isf" $verzeichnisRadio = Iniread(@scriptdir&"\verzeichnis.ini", "Verzeichnis", "PfadRadio", ""); GUISetState(@SW_SHOW,$ChooseScript) $aArray = _FileListToArrayRec($verzeichnisRadio & "\", "Setup.vbs||*_bak*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_SORT) $top = 10 For $ar = 1 To $aArray[0] Assign("Radio" & $ar, GUICtrlCreateRadio($aArray[$ar], 10, $top, 350, 20)) ;MsgBox(0,"",$aArray[$ar]) $top += 30 Next While 1 $nMsg = GUIGetMsg() Switch $nMsg .... Big thank you for the help. Now i understand the GUI handling better and also the to work with arrays. Now i build the code in my main script and test it.1 point -
Problem with GUICtrlRead in second GUI
JB72 reacted to abberration for a topic
OK, I think I understand the situation a little better. GUI1 should be your main GUI and GUI2 should be the radio selection (I think). Therefore you might want to structure your GUI2 to do all the reading file locations, making the radios and writing to the INI. Just for an example, I had the following code to write your selection in an INI in the script directory (and a little sample code (_WriteToINI) if you want to put INI writing off to another function). I might be wrong about all this, but here's an idea of how this might work... #include <Array.au3> #include <File.au3> #include <MsgBoxConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> $Form1 = GUICreate("Form1", 400, 278, 192, 124) $Button1 = GUICtrlCreateButton("Choose", 264, 208, 75, 25, $WS_GROUP) GUISetState(@SW_SHOW) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 _CreateRadios() EndSwitch WEnd Func _CreateRadios() $Form2 = GUICreate("Form2", 300, 293, 700, 218) $top = 10 $aArray = _FileListToArrayRec(@ScriptDir, "Setup.vbs||*_bak*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_SORT) For $ar = 1 To $aArray[0] Assign("Radio" & $ar, GUICtrlCreateRadio($aArray[$ar], 10, $top, 350, 20)) $top += 30 Next $Button2 = GUICtrlCreateButton("Select", 136, 136, 75, 25, $WS_GROUP) GUISetState(@SW_SHOW) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE GUIDelete($Form2) ExitLoop Case $Button2 For $ar = 1 To $aArray[0] If GUICtrlRead(Eval("Radio" & $ar)) = $GUI_CHECKED Then IniWrite(@ScriptDir & "\verzeichnis.ini", "Verzeichnis", "VBS", GUICtrlRead(Eval("Radio" & $ar), 1)) _WriteToINI($aArray, $ar) MsgBox(0, "", "You chose: " & GUICtrlRead(Eval("Radio" & $ar), 1) & @CRLF & "It has been written to the INI @ script folder") EndIf Next GUIDelete($Form2) ExitLoop EndSwitch WEnd EndFunc ;==>_CreateRadios Func _WriteToINI($aArray, $ar) ; Other stuff you may want to write to an INI $verzeichnis = "scripts" & $aArray[$ar] IniWrite(@ScriptDir & "\verzeichnis.ini", "Verzeichnis", "VBS", $verzeichnis) $verzeichnis = @ScriptDir & "\scripts\" & StringRegExpReplace($aArray[$ar], "\\Setup.vbs", "") IniWrite(@ScriptDir & "\verzeichnis.ini", "Verzeichnis", "Pfad", $verzeichnis) EndFunc ;==>_WriteToINI1 point -
Just chiming in here a little bit. It's possible that the VPN connection is blocking ping / ICMP. If browsing still works, that means that DNS and HTTP/HTTPS is working properly. You could try a trace route (tracert) both on and off VPN to see where the pings stop.1 point