Search code examples
autoit

AutoIt: Find window under mouse pointer


I'm using AutoIt3 and I need a way for the user to select a window. The fastest method is, in my opinion, having them point to a window. So the question is, how do I see what window is under their mouse pointer?


Solution

  • I extrapolated this from some code I had laying around for selecting areas on the screen. This will just pop up the Window title thats under the mouse (hit Escape to exit the loop):

    #include <WinAPI.au3>
    #include <Misc.au3>
    
    Func _WindowFromPoint($iX,$iY)
        Local $stInt64,$aRet,$stPoint=DllStructCreate("long;long")
        DllStructSetData($stPoint,1,$iX)
        DllStructSetData($stPoint,2,$iY)
        $stInt64=DllStructCreate("int64",DllStructGetPtr($stPoint))
        $aRet=DllCall("user32.dll","hwnd","WindowFromPoint","int64",DllStructGetData($stInt64,1))
        If @error Then Return SetError(2,@error,0)
        If $aRet[0]=0 Then Return SetError(3,0,0)
        Return $aRet[0]
    EndFunc
    
    Local $hControl, $hWin, $hOldWin, $aMousePos
    $hOldWin = ""
    While Not _IsPressed("1B")
        $aMousePos = MouseGetPos()
        $hControl=_WindowFromPoint($aMousePos[0],$aMousePos[1])
        ; Since _WindowFromPoint() can return 'sub' windows, or control handles, we should seek the owner window
        $hWin=_WinAPI_GetAncestor($hControl,2)
        If $hWin <> $hOldWin Then
            TrayTip("Window Info","Window under mouse = " & WinGetTitle($hWin), 1)
            $hOldWin = $hWin
        EndIf
        Sleep(10)
    WEnd