VB.NET WinForm获取运行程序用户名

时间:2022-10-20 08:40:38

一个程序也许会被多个用户运行,如下:
VB.NET WinForm获取运行程序用户名

那在VB.NET的WinForm环境下,怎样获取User Name呢?
可从下面的方法:
VB.NET WinForm获取运行程序用户名

代码:

Public Shared Function GetProcessOwner(ByVal ProcessName As String) As String
Dim po = String.Empty
Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(selectQuery)
Dim moc As ManagementObjectCollection = searcher.Get()
For Each proc As ManagementObject In moc
Dim s() As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
If proc("Name").ToString() = ProcessName & ".exe" Then
po = s() & "\\" & s()
End If
Next
Return po
End Function