Ralf Westphal Archiv

weblogs.asp.net

Check for logged on user on Windows machine

3. Jan. 2004Erstveröffentlichung: weblogs.asp.net/ralfwOriginaladresseralfw.de/archiv/2004/check-for-logged-on-user-on-windows-machine/

Motivated by a posting in a user group I tried to find the answer to the question: How can a Windows Service find out, if a user has already logged onto the machine it is running on?

I googled for a while and it seems, there is no simple function like "IsUserLoggedOn" in the Win32 API or in the .NET Fx base class library. But I stumbled across a hint which pointed into the direction of WMI as a solution.

So here is my VB.NET version of the function IsUserLoggedOn(). It gets a list of all processes on a machine from WMI and asks each one for the name of the user it is running under. So if a Windows Service is checking for a certain user, e.g. John Doe, if he has already logged on, it just needs to call the function periodically. (If instead it wants to check if any user has logged on, it needs to see, if processes exist running under a non-system account.)

Imports System.Management

Module Module1
    Sub Main()
        Console.WriteLine(IsUserLoggedOn("John Doe"))
    End Sub

Private Function IsUserLoggedOn(ByVal userName As String) As Boolean
        Dim mc As New ManagementClass("Win32_Process")
        Dim moc As ManagementObjectCollection = mc.GetInstances
        Dim mo As ManagementObject
        For Each mo In moc
            Dim p As New ROOT.CIMV2.Process(mo)

Dim processDomain, processUser As String
            p.GetOwner(processDomain, processUser)
            If processUser = userName Then
                Return True
            End If
        Next
    End Function
End Module

For this code to work you need to reference the WMI library assembly System.Management in your project. Then download the WMI Server Explorer Add-In for VS.NET 2003 (see resources below) and create a managed class (ROOT.CIMV2.Process) for the Processes node in the Management Classes branch of the server explorer. Include the above function IsUserLoggedOn() and you´re set.

Resources:

-A introductory article on WMI:
http://msdn.microsoft.com/msdnmag/issues/02/05/WMIMan/default.aspx

-Download link for WMI Server Explorer Add-In for VS.NET 2003
http://www.microsoft.com/downloads/details.aspx?familyid=62d91a63-1253-4ea6-8599-68fb3ef77de1&displaylang=en

← Zurück ins Archiv