How to find out the owner / user running a process

sizo

Member
Joined
Jun 17, 2011
Messages
5
Programming Experience
Beginner
Hi All,

I'm fairly new to vb.net and seem to be struggling to get a piece of information I need for a project at work!

Basically I can list all the applications running on a machine, I cannot however retrieve the details of the user running it!

At the moment I'm using the following code after importing System.ServiceProcess and System.Diagnostics.Process:

Public Sub GetProcess()
Dim pr As Process
A = 0
For Each pr In Process.GetProcesses(System.Environment.MachineName)
ReDim Preserve arrProcess(A)
arrProcess(A) = New String() {pr.ProcessName.ToString, Process.GetCurrentProcess.PrivateMemorySize64}
A = A + 1
Next
End Sub


I have tried using pr.StartInfo.UserName but that just returns the username of the person logged onto the machine.

Any help would be much appreciated!

Thank you!

Simon
 
You can use OpenProcessToken API call and create a WindowsIdentity from the returned token handle, then get name from identity.
 
Thanks for a quick response John. As i've never used OpenProcessToken API call, would you be able to reference me to any web pages with good examples of code used so i can get a understanding of how i could go about resolving my problem? I've tried to find some myself, but i'm not too sure whether I'm on the right tracks!

Thanks again
 
MSDN has the documentation, for example: OpenProcessToken Function (Windows)
pinvoke.net may give you some declarations, here for example: pinvoke.net: OpenProcessToken (advapi32)

Here's a code example:
For Each p As Process In Process.GetProcesses
    Try
        Dim hToken As IntPtr
        If OpenProcessToken(p.Handle, Security.Principal.TokenAccessLevels.Query, hToken) Then
            Using wi As New Security.Principal.WindowsIdentity(hToken)
                Debug.WriteLine("{0} : {1}", p.ProcessName, wi.Name)
            End Using
            CloseHandle(hToken)
        End If                
    Catch ex As Exception
        Debug.WriteLine("{0} : {1}", p.ProcessName, ex.Message)
    End Try            
Next

Try-Catch is necessary because Process class can't get Handle for some reserved processes.
 
Thanks again John, I've used parts of your code with some from the pinvoke.net example. The only problem i have now is that CloseHandle is not declared. I managed to define OpenHandle from the pinvoke example, but it doesn't state how to define the close handle? Or have i misunderstood something obvious?
 
There's a search box at pinvoke, search CloseHandle :)
 
Back
Top