我正在创建一个查找进程的程序,并且可以查看哪个用户正在使用它们。我有扫描代码,但没有用户名代码。用户名必须是字符串。例如:我有2个人运行一些进程,进程将显示在列表视图中。第一列用于进程,第二列用于用户名。我希望它像:
(在此处理)(此处为用户名)
(在此处理)(此处为用户名)....
你明白了我的观点,而且计算机上运行的进程要多得多。问题是:如何获得使用该流程的人的用户名?
编辑:代码。这是我的代码。
For Each pr As Process In Process.GetProcesses
Dim lvi As ListViewItem = ListView1.Items.Add(CStr(pr.ProcessName))
'Now I need something to put for the username
Next
这是最常见的另一个。
Public Function GetProcessOwner(processId As Integer) As String
Dim query As String = "Select * From Win32_Process Where ProcessID = " + processId
Dim searcher As New ManagementObjectSearcher(query)
Dim processList As ManagementObjectCollection = searcher.[Get]()
For Each obj As ManagementObject In processList
Dim argList As String() = New String() {String.Empty, String.Empty}
Dim returnVal As Integer = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
' argList(0) == User
' argList(1) == DOMAIN
Return argList(0)
End If
Next
Return "NO OWNER"
End Function
答案 0 :(得分:2)
此代码取自here,您可以在此处找到更多信息。基本上,在控制台应用程序上,这会将进程名称和用户打印到屏幕上:
Public Shared Sub Main()
Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
Dim searcher As ManagementObjectSearcher = New
ManagementObjectSearcher(selectQuery)
For Each proc As ManagementObject In searcher.Get
Console.WriteLine(proc("Name").ToString)
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Console.WriteLine(("User: " & (s(1) + ("\\" + s(0)))))
Next
Console.ReadLine()
End Sub
这可以作为一个函数实现,如:
Public Function GetUserName(ByVal ProcessName As String)
Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(selectQuery)
Dim y As System.Management.ManagementObjectCollection
y = searcher.Get
For Each proc As ManagementObject In y
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Dim n As String = proc("Name").ToString()
If n = ProcessName & ".exe" Then
Return ("User: " & s(1) & "\\" & s(0))
End If
Next
End Function
仅供参考,proc.InvokeMethod("GetOwner", CType(s, Object()))
将返回如下数组:
在我们的案例中,会将其存储在s(1)
中。
希望这会有所帮助:)
如果函数返回类似User: \\
的内容,则该过程可能是一个特殊的窗口过程。要查看哪些进程将像这样(对于Windows用户):
<小时/>
VB.NET功能已被编辑,现在应该可以工作,虽然我不知道为什么控制台程序仍然有效。无论如何,如果它仍然有效,为什么要改变呢?