Cory Smith

Cory Smith

  • 2.2k
  • 3
  • 253

Determining if a local user account is logged into Windows.

Sep 22 2023 8:28 PM

I am trying to see if a windows user account is logged in or not. Here is my current code:

Dictionary<string, ManagementObject> userMap = new Dictionary<string, ManagementObject> ();

private void popUserList()
    ManagementObjectSearcher usersSearcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_UserAccount");
    ManagementObjectCollection users = usersSearcher.Get();

    var localUsers = users.Cast<ManagementObject>().Where(
        u => (bool)u["LocalAccount"] == true &&
             int.Parse(u["SIDType"].ToString()) == 1 &&
             u["Name"].ToString() != "HomeGroupUser$"

    foreach (ManagementObject user in localUsers)
        userMap[user["Name"].ToString()] = user;

private ManagementObject getCurrentUser()
    return userMap[userAccountLst.SelectedItem.ToString()];

private bool IsUserLoggedIn(ManagementObject user)
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserProfile WHERE Loaded = True");

    foreach (ManagementObject obj in searcher.Get())
        if (obj["Antecedent"].ToString().Contains(getCurrentUser()["Name"].ToString()))
            return true;

    return false;

I have a WinForms application that has a Listbox with all the user accounts list in it, for context.

However, unbeknownst to me, Win32_UserProfile doesn't work anymore. It's not anywhere in Microsoft's documentation. Assumingly deprecated. I've been looking around Google for hours trying to get a method that is not:

a. Getting if a user account is logged in on ASP.NET.
b. Getting if a user account is logged in via Remote Connection.
c. Getting what the CURRENT user account is.

I just want to input a user as a ManagementObject, and get if it is logged into Windows LOCALLY.

Answers (2)