Sign in to follow this  
Followers 0
Nahuel

_ProcessGetPid()

6 posts in this topic

#1 ·  Posted (edited)

It may have been done before, but still.

;________________________________________________________________________________
;Description: Returns the Process ID's (PID) of a given process name.
;Parameters -  $sName: The name (ending with .exe) of a currently running process.
;Return value: An array containing the Process ID's (PID)
;               Element 0 contains number of occurences.
;Author: Nahuel
;__________________________________________________________________________________
Func _ProcessGetPid($sName)
    If Not ProcessExists($sName) Then
        SetError(1)
        Return ""
    EndIf
    Local $aPList=ProcessList($sName)
    If @error Then Return ""
    Local $aMatches[UBound($aPList)]
    $aMatches[0] = $aPList[0][0]
    For $i=1 To $aPList[0][0]
        $aMatches[$i] = $aPList[$i][1]
    Next
    Return $aMatches
EndFunc

Example:

$Pid=_ProcessGetPid("svchost.exe")

For $i=1 To $Pid[0]
    MsgBox(0,"","svchost.exe's PID: " & $Pid[$i])
Next

-edit-

I just noticed that _ProcessGetName() works on a similar way... so why hasn't something like this been included in Process.au3?

Edited by Nahuel

Share this post


Link to post
Share on other sites



And why ProcessExists() is not good for such task? :)

And yes, Process.au3 library should be expanded, i have many functions in seperated examples, i can collect them to one UDF library.. fucntions such as _ProcessPathExists(), _ProcessGetPath(), they are very usefull...


Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

AutoIt is simple, subtle, elegant. © AutoIt Team

Share this post


Link to post
Share on other sites

And why ProcessExists() is not good for such task? :)

Didn't you ask me this already? Look

Run("notepad.exe")
Run("notepad.exe")
Run("notepad.exe")

Sleep(1000)

;Using ProcessExist()
$Pid=ProcessExists("notepad.exe")
MsgBox(0,"ProcessExist()","Notepad's pid: " & $Pid)

;Using _ProcessGetPid()
$Pid=_ProcessGetPid("notepad.exe")

For $i=1 To $Pid[0]
    MsgBox(0,"_ProcessGetPid()","Notepad's pid: " & $Pid[$i])
Next

;________________________________________________________________________________
;Description: Returns the Process ID's (PID) of a given process name.
;Parameters -  $sName: The name (ending with .exe) of a currently running process.
;Return value: An array containing the Process ID's (PID)
;            Element 0 contains number of occurences.
;Author: Nahuel
;__________________________________________________________________________________
Func _ProcessGetPid($sName)
    If Not ProcessExists($sName) Then
        SetError(1)
        Return ""
    EndIf
    Local $aPList=ProcessList($sName)
    If @error Then Return ""
    Local $aMatches[UBound($aPList)]
    $aMatches[0] = $aPList[0][0]
    For $i=1 To $aPList[0][0]
        $aMatches[$i] = $aPList[$i][1]
    Next
    Return $aMatches
EndFunc

Share this post


Link to post
Share on other sites

Oh i see, sorry, now i see that this func return the PID's of all processes with certain name :P

Please accept my apology, and Happy new Year to you! :)


Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

AutoIt is simple, subtle, elegant. © AutoIt Team

Share this post


Link to post
Share on other sites

Haha, appology accepted :) It's just different because ProcessExist() will return only one pid of a process that may have many occurences. This func will return an array will all of them. It's nothing you couldn't figure out by yourself, but since Process.au3 has _ProcessGetName() ...

I'm very interested in your UDF's, specially _ProcessGetPath(). I'll check it out now!

Happy New Year to you too!!

Share this post


Link to post
Share on other sites

Here are _ProcessGetPath() and _ProcessPathExists()...

;===============================================================================
;
; Function Name:    _ProcessGetPath()
; Description:      Get the executable path of certain process.
;
; Parameter(s):     $vProcess - PID or name of a process.
;
; Requirement(s):   AutoIt v3.2.8.1 or higher.
;                   Kernel32.dll (included with Windows)
;                   Psapi.dll (included with most Windows versions)
;
; Return Value(s):  On Success - Returns full path to the executed process.
;                   On Failure - Returns -1 and sets @Error to:
;                                                               1 - Given process not exists.
;                                                               2 - Error to call Kernel32.dll.
;                                                               3 - Error to open Psapi.dll.
;                                                               4 - Unable to locate path of executed process,
;                                                                   (or can be other error related to DllCall).
;
; Author(s):        G.Sandler (a.k.a CreatoR) - CreatoR's Lab (http://creator-lab.ucoz.ru)
;
;===============================================================================
Func _ProcessGetPath($vProcess)
    Local $iPID = ProcessExists($vProcess)
    If Not $iPID Then Return SetError(1, 0, -1)
    
    Local $aProc = DllCall('kernel32.dll', 'hwnd', 'OpenProcess', 'int', BitOR(0x0400, 0x0010), 'int', 0, 'int', $iPID)
    If Not IsArray($aProc) Or Not $aProc[0] Then Return SetError(2, 0, -1)
    
    Local $vStruct = DllStructCreate('int[1024]')
    
    Local $hPsapi_Dll = DllOpen('Psapi.dll')
    If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@SystemDir & '\Psapi.dll')
    If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@WindowsDir & '\Psapi.dll')
    If $hPsapi_Dll = -1 Then Return SetError(3, 0, '')
    
    DllCall($hPsapi_Dll, 'int', 'EnumProcessModules', _
        'hwnd', $aProc[0], _
        'ptr', DllStructGetPtr($vStruct), _
        'int', DllStructGetSize($vStruct), _
        'int_ptr', 0)
    Local $aRet = DllCall($hPsapi_Dll, 'int', 'GetModuleFileNameEx', _
        'hwnd', $aProc[0], _
        'int', DllStructGetData($vStruct, 1), _
        'str', '', _
        'int', 2048)
    
    DllClose($hPsapi_Dll)
    
    If Not IsArray($aRet) Or StringLen($aRet[3]) = 0 Then Return SetError(4, 0, '')
    Return $aRet[3]
EndFunc

;===============================================================================
;
; Function Name:    _ProcessPathExists()
; Description:      Check if given path is an existing process.
;
; Parameter(s):     $sPath - Path of executable to check.
;
; Requirement(s):   AutoIt v3.2.8.1 or higher.
;                   Kernel32.dll (included with Windows)
;                   Psapi.dll (included with most Windows versions)
;
; Return Value(s):  On Success - Returns PID of executable process, @extended include total number of similar processes runing.
;                   On Failure - Returns False and sets @Error to:
;                                                               1 - Given path not exists.
;                                                               2 - Process with name of the executable not exists.
;                                                               3 - Error to open Psapi.dll.
;                                                               4 - Error to call Kernel32.dll.
;                                                               5 - Unknown/other error related to DllCalls.
;
; Author(s):        G.Sandler (a.k.a CreatoR) - CreatoR's Lab (http://creator-lab.ucoz.ru)
;
;===============================================================================
Func _ProcessPathExists($sPath)
    If Not FileExists($sPath) Then Return SetError(1, 0, False)
    
    Local $sPathName = StringRegExpReplace($sPath, "^.*\\", "")
    Local $aProcList = ProcessList($sPathName)
    
    If Not ProcessExists($sPathName) Then Return SetError(2, 0, False)
    Local $iUbound = UBound($aProcList)-1
    
    Local $hPsapi_Dll = DllOpen('Psapi.dll')
    If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@SystemDir & '\Psapi.dll')
    If $hPsapi_Dll = -1 Then $hPsapi_Dll = DllOpen(@WindowsDir & '\Psapi.dll')
    If $hPsapi_Dll = -1 Then Return SetError(3, 0, False)
    
    Local $aProc, $aPath
    Local $vStruct = DllStructCreate('int[1024]')
    
    For $i = 1 To $iUbound
        $aProc = DllCall('kernel32.dll', 'hwnd', 'OpenProcess', 'int', BitOR(0x0400, 0x0010), 'int', 0, 'int', $aProcList[$i][1])
        If Not IsArray($aProc) Or Not $aProc[0] Then Return SetError(4, 0, False)
        
        DllCall($hPsapi_Dll, 'int', 'EnumProcessModules', _
            'hwnd', $aProc[0], _
            'ptr', DllStructGetPtr($vStruct), _
            'int', DllStructGetSize($vStruct), _
            'int_ptr', 0) 
        
        $aPath = DllCall($hPsapi_Dll, 'int', 'GetModuleFileNameEx', _
            'hwnd', $aProc[0], _
            'int', DllStructGetData($vStruct, 1), _
            'str', '', _
            'int', 2048)
        
        If IsArray($aPath) And $aPath[3] = $sPath Then
            DllClose($hPsapi_Dll)
            Return SetExtended($iUbound, $aProcList[$i][1])
        EndIf
    Next
    
    DllClose($hPsapi_Dll)
    Return SetError(5, 0, False)
EndFunc

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

AutoIt is simple, subtle, elegant. © AutoIt Team

Share this post


Link to post
Share on other sites

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
Sign in to follow this  
Followers 0