Search code examples
vb.netwinforms.net-2.0

VB.Net 2.0 Windows Forms - How do I get the executing User


I have a .Net 2.0 Windows Forms application which needs to be run as a specific user (right click, run as).

I need to be able to check which user has launched it and stop if it is not the specific user.

All the examples I have found show the logged in user.

How can I access the application executing username?


Solution

  • Based on this, with a little bit of help from this, I came up with this:

    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