2014-10-09 96 views
3

如何獲取正在運行的進程的程序名稱和任務ID。 shell()返回發起的進程的任務ID。類似的,我想獲得已經運行並且不是由宏創建的進程的任務ID和名稱。我發現代碼,返回程序的名稱,但它的輸出缺少任務ID信息:VBA獲取正在運行的進程的程序名稱和任務ID

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 
+0

使用ProcessId而不是名稱在上面的腳本不起作用 – Qbik 2014-10-09 12:37:03

回答

2

您可以更改SQL讀取Select Name, ProcessID FROM Win32_Process

然後在你的For循環,以獲取在需要的地方使用Process.Properties_("Name").valueProcess.Properties_("ProcessID").value

+0

是否有一些更簡單的方法來獲取任務ID,然後使用WMI對象? – Qbik 2014-10-09 14:32:06

相關問題