我有以下函数用于标识启动特定进程的用户的用户名:
Private Function GetProcessAssociatedUserID(ByVal processName As String) As String
Dim user(1) As String
Try
Dim query As New SelectQuery(processName)
Dim searcher As New System.Management.ManagementObjectSearcher(query)
For Each process As ManagementObject In searcher.Get()
process.InvokeMethod("GetOwner", CType(user, Object()))
Next
Catch ex As Exception
End Try
Return user(0)
End Function
然而,在ForEach启动的某个地方,我得到了这个" ManagementException被抓住了:无效的课程"异常抛入我的catch块。我已经通过调试但仍然无法解决问题。任何帮助将不胜感激。
答案 0 :(得分:0)
你可以尝试这样做
Private Function GetProcessAssociatedUserID(ByVal processName As String) As String
Dim query = "Select * from Win32_Process Where Name = """ + processName + """"
Dim searcher = New ManagementObjectSearcher(query)
Dim processList = searcher.Get()
For Each mObj As ManagementObject In processList
Dim argList As String() = {String.Empty, String.Empty}
Dim returnVal = Convert.ToInt32(mObj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
Return argList(1) + "\\" + argList(0)
End If
Next
Return ""
End Function
此代码段适用于.NET Framework 3.5及更高版本。有关详细信息,请参阅using-managementobjectsearcher-in-systemmanagement-is-getting-compiling-errors