This is a small Windows service program which retrieves the username of the currently logged in user. There might arise some situations when you need to have this information through a Windows service. If we use traditional API functions like
GetUserNameEx, they simply return the user name of the process account under which that Windows service is running. It is the SYSTEM account in most cases. The above mentioned API functions always return SYSTEM as the currently logged in user.
To over come this problem, we can use Windows Management Instrumentation (WMI) classes. The main idea is that we get the username of the Explorer process under which it is running. And we know that the Explorer process is always running under the account with which the current user has been logged in.
To use this code you need to download a WMI plug-in from here. It will install WMI extensions for Visual Studio .NET 2003 Server Explorer. Now follow the steps as mentioned:
- Create a Windows Service project using VB.NET.
- Open Server Explorer and expand the tree node which says Management Classes.
- Right click on Processes node and select "Generate Managed Class". This will add a reference to the
- Now import
System.Management namespace in your project (Service1.vb).
- In the
OnStart procedure, add the following code:
Dim mc As New ManagementClass("Win32_Process")
Dim moc As ManagementObjectCollection = mc.GetInstances
Dim mo As ManagementObject
Dim processDomain, processUser As String
For Each mo In moc
Dim p As New ROOT.CIMV2.Process(mo)
If (p.Name.Trim = "explorer.exe") Then
The simple explanation of the above code is that it loops through all the running processes on the system and as it finds the "explorer.exe" process, it returns its username. And this is the username of the currently logged in user as well.
You can print this user name in a file by adding the following code:
Dim myFile As New _
Install the Windows service using InstallUtil and run and test it. For this purpose, read other articles on how to install and run a Windows service.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.