Re: Getting logged in user from a service?



James,

I'm assuming you are using the Process class or something similar? If
so, you can get the handle to the process through the Handle property.

Once you have that, you can call OpenProcessToken (through the P/Invoke
layer) to open the process token for reading. Once you have that, you can
then call the GetTokenInformation function (again through the P/Invoke
layer) to get the SID of the user that began the process.

Finally, you can call the LookupAccountSid API function using the
pointer to the SID to get the domain name, user name, etc, etc.

Make sure you call CloseHandle on the token you get from the call to
GetTokenInformation.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx

"JamesB" <james@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:466420cf$0$27858$db0fefd9@xxxxxxxxxxxxxxxxx
I am writing a service that monitors when a particular app is started.
Works, but I need to get the user who is currently logged in, and of
course Environment.UserName returns the service logon
(NT_AUTHORITY\SYSTEM).

I understand that when the service starts, no user may be logged in, but
that's ok, as the app I am monitoring can only be run by a logged in user.
Do I need to use WMI to get the user context of Explorer.exe or is there a
neater way?

James.


.


Loading