Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Getting program names and task ID of running processes

Tags:

vba

How to get program names and task IDs of running processes. shell() returns task ID of initiated process. Similar, I would like to get the task ID and name of processes which are already running and is not created by macro. I've found code which returns programs names but its output lacks task IDs information :

http://www.vbaexpress.com/forum/archive/index.php/t-36677.html

Sub Test_AllRunningApps()
    Dim apps() As Variant
    apps() = AllRunningApps

    Range("A1").Resize(UBound(apps), 1).Value2 = WorksheetFunction.Transpose(apps)
    Range("A:A").Columns.AutoFit
End Sub

'Similar to: http://msdn.microsoft.com/en-us/library/aa393618%28VS.85%29.aspx
Public Function AllRunningApps() As Variant
    Dim strComputer As String
    Dim objServices As Object, objProcessSet As Object, Process As Object
    Dim oDic As Object, a() As Variant

    Set oDic = CreateObject("Scripting.Dictionary")

    strComputer = "."

    Set objServices = GetObject("winmgmts:\\" _
        & strComputer & "\root\CIMV2")
    Set objProcessSet = objServices.ExecQuery _
        ("SELECT Name FROM Win32_Process", , 48)

    For Each Process In objProcessSet
       If Not oDic.exists(Process.Name) Then oDic.Add Process.Name, Process.Name
    Next

    a() = oDic.keys

    Set objProcessSet = Nothing
    Set oDic = Nothing

    AllRunningApps = a()
End Function
like image 816
Qbik Avatar asked Oct 09 '14 11:10

Qbik


1 Answers

You can change the SQL to read Select Name, ProcessID FROM Win32_Process

Then in your For Loop, to get the name use Process.Properties_("Name").value and Process.Properties_("ProcessID").value where needed.

like image 98
JNevill Avatar answered Nov 15 '22 08:11

JNevill