`
Windows API: Getting user name using process handle 2006-09-04 -- Jim Kane > I run a program in mode service. So the user is "SYSTEM" in all the > session of the computer. I would like to retreive the user that is > currently log. When I try via Valutilities for example, it always return > "SYSTEM" but not the user currently log. > Does someone has an idea , is there some environnement variable I could > read from my program that contains the name of the user actually log ? Not easy to do. In fact I just read an article about why there can be many even without citrix/teminal services so it can be very tricky: http://blogs.msdn.com/oldnewthing/archive/2006/08/22/712677.aspx Here is how to do it: 1. Enumerate all processes - presumably the user you are interested in is running a particular program. His name appears as the account next to in in the ctrl-alt-delete list. Obtain the PID (process id ) of that process. Alternatively you could run this sequence of steps on all processes until you find one not running in a system account - not guaranteed to be the logged on user but probably is especially if that account is running multple processes. 2. Call OpenProcess() using the PID from step 1 to get an hProcess (eventually call closehandle(hProcess) 3. Call OpenProcessToken() to get a hToken using the hProcess. ( Eventually call closehandle( htoken ) ) 4. Call GetTokenInformat( htoken, 1, address( buffer ), size(buffer), byteswrittenIntoBuffer ) there should now be only 1 sid in your buffer. (sid is a security id ) 5. Call LookUpAccountSid(0, address(buffer) , address(username), size(username), address(userdomain), size( userdomain), ReturnedSidType) You now have the username and his/her domain. 6. free the buffer allocated in step 4. call closehandle() as indicated above. The calls in steps 4 and 5 are actually a two step process. The 1st time you call you get the size of the buffer you need. You then use NEW() to create the required buffer and call again to get the actual info. Jim Kane Printed November 21, 2024, 7:23 am This article has been viewed/printed 35208 times. Google search has resulted in 32 hits on this article since January 25, 2004. |