Jump to content

get the process from window and vice versa


Recommended Posts

hi, I've been using auto it for years but I'm a little stumped.  

I'm trying to find a short and sweet way to get the windows associated with a process and find out what process is associated with a window.

ideally I'd like functions like:

 

$process = "Firefox.exe"

$windowHandle = [some window handle ]

GetProcessFromWindowHandle($windowHandle) (returns the name of a process)

GetWindowHandlesFromProcess($process)

(returns an array with a list of all the windows associated with the process)

 

any ideas? preferably something with a small Big O (ie not searching every open process or window, so maybe some api function or built in function I'm probably missing or something else)

 

 

Link to comment
Share on other sites

I hope this helps:

#include <Array.au3>
#include <WinAPIProc.au3>

Global $tag_SYSTEM_THREADS = "double KernelTime;" & _
        "double UserTime;" & _
        "double CreateTime;" & _
        "ulong  WaitTime;" & _
        "ptr    StartAddress;" & _
        "dword  UniqueProcess;" & _
        "dword  UniqueThread;" & _
        "long   Priority;" & _
        "long   BasePriority;" & _
        "ulong  ContextSwitchCount;" & _
        "long   State;" & _
        "long   WaitReason"

Global $tag_SYSTEM_PROCESSES = "ulong  NextEntryDelta;" & _
        "ulong  Threadcount;" & _
        "ulong[6];" & _              ; Reserved...
        "double CreateTime;" & _
        "double UserTime;" & _
        "double KernelTime;" & _
        "ushort Length;" & _                 ; unicode string length
        "ushort MaximumLength;" & _    ; also for unicode string
        "ptr    ProcessName;" & _                ; ptr to mentioned unicode string - name of process
        "long   BasePriority;" & _
        "ulong  ProcessId;" & _
        "ulong  InheritedFromProcessId;" & _
        "ulong  HandleCount;" & _
        "ulong[2];" & _              ;Reserved...
        "uint    PeakVirtualSize;" & _
        "uint    VirtualSize;" & _
        "ulong   PageFaultCount;" & _
        "uint    PeakWorkingSetSize;" & _
        "uint    WorkingSetSize;" & _
        "uint    QuotaPeakPagedPoolUsage;" & _
        "uint    QuotaPagedPoolUsage;" & _
        "uint    QuotaPeakNonPagedPoolUsage;" & _
        "uint    QuotaNonPagedPoolUsage;" & _
        "uint    PagefileUsage;" & _
        "uint    PeakPagefileUsage;" & _
        "uint64 ReadOperationCount;" & _
        "uint64 WriteOperationCount;" & _
        "uint64 OtherOperationCount;" & _
        "uint64 ReadTransferCount;" & _
        "uint64 WriteTransferCount;" & _
        "uint64 OtherTransferCount"


Global $hWND , $aResult = _WinAPI_EnumProcesses("Firefox.exe")
For $i = 0 To UBound($aResult) - 1
    $hWND = _WinAPI_GetHWNDFromPid($aResult[$i][1])
    ConsoleWrite("Window handle: " & $hWND & @CRLF)
    ConsoleWrite("Process name: " & _WinAPI_GetProcessNameFromHWND($hWND) & @CRLF)
Next

Func _WinAPI_GetHWNDFromPid($iPid)
    Local $aData = _WinAPI_EnumProcessWindows($iPid, 1)
    If @error Then Return SetError(1, 0, 0)
    Return $aData[1][0]
EndFunc

Func _WinAPI_GetProcessNameFromHWND($hWND, $bFullpath = False)
    Local $sResult = _WinAPI_GetWindowFileName($hWND)
    If @error Then Return SetError(1, 0, 0)
    If $bFullpath Then Return $sResult
    Return StringRegExpReplace($sResult, ".+\\(.+?)", "$1")
EndFunc

Func _WinAPI_EnumProcesses($sProcessName = "") ;http://www.autoitscript.com/forum/index.php?showtopic=88934
    Local $ret = DllCall("ntdll.dll", "int", "ZwQuerySystemInformation", "int", 5, "int*", 0, "int", 0, "int*", 0)
    Local $Mem = DllStructCreate("byte[" & $ret[4] & "]")
    Local $ret = DllCall("ntdll.dll", "int", "ZwQuerySystemInformation", "int", 5, "ptr", DllStructGetPtr($Mem), "int", DllStructGetSize($Mem), "int*", 0)
    Local $SysProc = DllStructCreate($tag_SYSTEM_PROCESSES, $ret[2])
    Local $SysProc_ptr = $ret[2]
    Local $SysProc_Size = DllStructGetSize($SysProc)
    Local $SysThread = DllStructCreate($tag_SYSTEM_THREADS)
    Local $SysThread_Size = DllStructGetSize($SysThread)
    Local $buffer, $i, $lastthread, $m = 0, $NextEntryDelta, $k, $temp, $space, $l
    Local $avArray[10000][2]
    While 1
        $buffer = DllStructCreate("char[" & DllStructGetData($SysProc, "Length") & "]", DllStructGetData($SysProc, "ProcessName"))
        For $i = 0 To DllStructGetData($SysProc, "Length") - 1 Step 2
            $avArray[$m][0] &= DllStructGetData($buffer, 1, $i + 1)
        Next
        $avArray[$m][1] = DllStructGetData($SysProc, "ProcessId")

        $NextEntryDelta = DllStructGetData($SysProc, "NextEntryDelta")
        If Not $NextEntryDelta Then ExitLoop
        $SysProc_ptr += $NextEntryDelta
        $SysProc = DllStructCreate($tag_SYSTEM_PROCESSES, $SysProc_ptr)
        If $sProcessName = "" Then
            $m += 1
        Else
            If $avArray[$m][0] = $sProcessName Then
                $m += 1
            Else
                $avArray[$m][0] = ""
            EndIf
        EndIf
    WEnd
    If $sProcessName <> "" Then $m -= 1
    ReDim $avArray[$m + 1][2]
    Return $avArray
EndFunc

 

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Link to comment
Share on other sites

I hope this helps:

Global $hWND , $aResult = _WinAPI_EnumProcesses("Firefox.exe")
For $i = 0 To UBound($aResult) - 1
    $hWND = _WinAPI_GetHWNDFromPid($aResult[$i][1])
    ;ConsoleWrite("Window handle: " & $hWND & @CRLF)
    ConsoleWrite("Window handle: " & $hWND &' - Title: '& WinGetTitle($hWND) &@CRLF) ; <-- all there, isn't it ?
    ConsoleWrite("Process name: " & _WinAPI_GetProcessNameFromHWND($hWND) & @CRLF)
Next

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Link to comment
Share on other sites

SleepyXtreme,

Building on SadBunny's suggestion...

;
;
;

#include <array.au3>

;---------------------------------------------
;  define arrays
;---------------------------------------------

local $list[300][4]                                                 ; 300 windows max
local enum $title, $handle, $pid, $exe                              ; enumerations for array offsets

;---------------------------------------------
;  get array of windows and populate $list
;---------------------------------------------

local $a1 = winlist()                                               ; get list of windows

for $i = 0 to $a1[0][0]                                             ; and copy title, handle and pid to $list array
    $list[$i][$title]   = $a1[$i][$title]                           ; window title
    $list[$i][$handle]  = $a1[$i][$handle]                          ; window handle
    $list[$i][$pid]     = wingetprocess($a1[$i][$handle])           ; owning process id
next

;---------------------------------------------
;  get array of processes and populate $list
;---------------------------------------------

local $a2 = processlist()                                           ; get list of processes

for $i = 0 to $a1[0][0]
    for $j = 0 to $a2[0][0]
        if $list[$i][2] = $a2[$j][1] then $list[$i][3] = $a2[$j][0] ; and copy process name to $list array
    Next
next

_arraysort($list,1,0,0,2)                                           ; sort the array by $pid desc



redim $list[$i][4]

_arraydisplay($list)

;---------------------------------------------
;  format output to console
;---------------------------------------------

local $savepid = '', $out = ''

for $i = 0 to ubound($list) - 1
    if $i = 0 then
        $out &= stringformat('%-10s%-15s',$list[$i][$pid],$list[$i][$exe]) & @crlf

        $savepid = $list[$i][$pid]
    endif

    if $list[$i][$pid] = '' then exitloop

    if  $savepid = $list[$i][$pid] then
        if $list[$i][$title] <> '' then $out &= @tab & @tab & $list[$i][$title] & @crlf

    else
        if $i <> 0 then $out &= stringformat('%-10s%-15s',$list[$i][$pid],$list[$i][$exe]) & @crlf

        $savepid = $list[$i][$pid]
    endif

next

consolewrite($out & @lf)

 

kylomas

Edited by kylomas
corrected goofy spacing

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

WinGetProcess is what i was looking for but it only covers the first question.  From what you guys gave me, I think i found what i was looking for

I'm working on a script to hide all the windows associated with a certain process.

Here's what I have so far:

Global $processList[4]
$processList[0] = 4
$processList[1] = "winword.exe"
$processList[2] = "firefox.exe"
$processList[3] = "notepad.exe"

Func ToggleHideProcess() ; Hides the windows associated with a process from processlist
    For $y = 1 To $processList[0]
        $WindowList = getWindowsFromProcess($processList[$y])
        If $WindowList <> 0 Then
            For $x = 1 To $WindowList[0][0]
                hideWindow($WindowList[$x][0])
            Next
        EndIf
    Next
EndFunc   ;==>ToggleHideProcess
Func getWindowsFromProcess($Process)
    $wArray = _WinAPI_EnumProcessWindows(ProcessExists($Process), True)
    If @error Then
        Return 0
    Else
        Return $wArray
    EndIf
EndFunc   ;==>getWindowFromProcess

Func hideWindow($windowHandle)
    WinSetState($windowHandle, "", @SW_HIDE)
EndFunc   ;==>hideWindow

 

Link to comment
Share on other sites

I completely forgot WinList, WinGetProcess, ProcessList and ProcessExists...:whistle:

 

Edited by UEZ

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Link to comment
Share on other sites

  • 8 years later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...