1

我有一个 .Net 2.0 Windows Forms 应用程序,需要以特定用户身份运行(右键单击,运行身份)。

我需要能够检查哪个用户启动了它,如果不是特定用户则停止。

我发现的所有示例都显示了登录用户。

如何访问执行用户名的应用程序?

4

2 回答 2

2

也许这会对您有所帮助:如何确定 C# 中进程的所有者?

它在 C# 中,但很容易转换为 VB.NET,只需在 Google 中搜索“C# to VB”即可:)

于 2012-06-26T09:48:21.553 回答
0

基于此,在的一些帮助下,我想出了这个:

Imports System.Runtime.InteropServices
Imports System.Security.Principal

Public Class GetProcessOwner

    <DllImport("advapi32.dll", SetLastError:=True)> _
    Public Shared Function OpenProcessToken(ByVal processHandle As IntPtr, ByVal desiredAccess As Integer, ByRef tokenHandle As IntPtr) As Boolean
    End Function

    <DllImport("kernel32.dll", SetLastError:=True)> _
    Public Shared Function CloseHandle(ByVal hObject As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    Private Const TokenQuery As UInteger = &H8

    Public Shared Function GetProcessOwner(ByVal processName As String) As String

        Dim ownerName As String = String.Empty

        For Each p As Process In Process.GetProcesses()

            If p.ProcessName = processName Then

                Dim ph As IntPtr = IntPtr.Zero

                Try
                    OpenProcessToken(p.Handle, TokenQuery, ph)
                    Dim wi As WindowsIdentity = New WindowsIdentity(ph)
                    ownerName = wi.Name

                Catch ex As Exception

                    ownerName = String.Empty

                Finally

                    If ph <> IntPtr.Zero Then
                        CloseHandle(ph)
                    End If

                End Try

            End If

        Next

        Return ownerName

    End Function

End Class
于 2012-06-26T15:46:17.280 回答