I’m writing a Windows Service using C# .NET 2005. How can I determine who the currently logged-on user is (if any)? Also is there a way to be notified when a user logs on?
Alternatively, is there a way to know who has recently used the machine?
I need to know the currently logged on user so I can cache some data for that user. Operating in a corporate environment there are thousands of potential users but it only makes sense to cache data for someone who uses that machine.
UPDATE:
This solution works well. Also see this pinvoke.net example which uses the extended structure to also retrieve domain name.
In combination with this I’m using the SystemEvents class to be notified when a user logs on to the machine. See example 2 here for a good example – note that you need to use a hidden form from a service in order to be able to use SystemEvents from a service.
You can use P/Invoke to call NetWkstaUserEnum, which will enumerate the currently logged on users. Keep in mind that there might be more than one user in case there are terminal server sessions, and that not all users returned is a “real” user. As the documentation states:
Here is a complete working code example in C# on how to call NetWkstaUserEnum: