1

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?

Shevek
  • 3,869
  • 5
  • 43
  • 63

2 Answers2

2

Maybe this will help you: How do I determine the owner of a process in C#?

It's in C# but that's easily converted to VB.NET, just search Google for "C# to VB" :)

Community
  • 1
  • 1
kor_
  • 1,510
  • 1
  • 16
  • 36
0

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
Shevek
  • 3,869
  • 5
  • 43
  • 63