Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Time elapsed since user logged in

Time elapsed since user logged in

Scheduled Pinned Locked Moved C#
data-structuresquestionworkspace
6 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Offline
    L Offline
    Lutoslaw
    wrote on last edited by
    #1

    Hi all! Via Environment.TickCount I can get time elapsed since system started. How could I get time elapsed since user logged in? An array containing all users who log in since the system starts last time and how long they stayed would be the best.

    Greetings - Gajatko

    H 1 Reply Last reply
    0
    • L Lutoslaw

      Hi all! Via Environment.TickCount I can get time elapsed since system started. How could I get time elapsed since user logged in? An array containing all users who log in since the system starts last time and how long they stayed would be the best.

      Greetings - Gajatko

      H Offline
      H Offline
      Hessam Jalali
      wrote on last edited by
      #2

      it can be done using WMI (System.Management namespace),I don't know but maybe .NET has some classes which give you these info. with WMI you can retrieve these data through Win32_LogonSession and Win32_LoggedOnUser and extract start time from them. with subtracting from DateTime.Now you'll have the duration it would be somewhat like this

      class UserLogonData
      {
          const string ALLUSERS = "All";
      
          readonly string userName;
          readonly DateTime loggedOnTime;
          string logonId;
      
          public string UserName
          {
              get { return this.userName; }
          }
          public DateTime LoggedOnTime
          {
              get { return this.loggedOnTime; }
          }
          public string LogonID
          {
              get { return this.logonId; }
          }
          public TimeSpan LoggedDuration
          {
              get { return DateTime.Now.Subtract(this.loggedOnTime); }
          }
      
          private UserLogonData(string userName, string logonId, DateTime loggedOnTime)
          {
              this.userName = userName;
              this.logonId = logonId;
              this.loggedOnTime = loggedOnTime;
          }
      
          public override string ToString()
          {
              return this.userName;
          }
      
          public static UserLogonData\[\] GetUsersLogonTime(string userName)
          {
              List dataList = new List();
      
              ManagementObjectSearcher mosUser = new ManagementObjectSearcher(new SelectQuery("Win32\_LoggedOnUser"));
              ManagementObjectSearcher mosSession = new ManagementObjectSearcher(new SelectQuery("Win32\_LogonSession"));
      
              ManagementObjectCollection mocUser = mosUser.Get();
              ManagementObjectCollection mocSession = mosSession.Get();
      
              foreach (ManagementObject moUser in mocUser)
              {
                  string userLogonAntecedentData = moUser.Properties\["Antecedent"\].Value.ToString();
                  string userLogonUserName = Regex.Replace(userLogonAntecedentData, @".\*Name=""(?'name'.+)"".\*", "${name}");
                  if (userName!=ALLUSERS && userLogonUserName != userName) continue;
                  string userLogonDependentData = moUser.Properties\["Dependent"\].Value.ToString();
                  string userLogonSessionId = Regex.Replace(userLogonDependentData, @".\*LogonId=""(?'id'\\d+)"".\*", "${id}");
                  foreach (ManagementObject moSession in mocSession)
                  {
      
      L 1 Reply Last reply
      0
      • H Hessam Jalali

        it can be done using WMI (System.Management namespace),I don't know but maybe .NET has some classes which give you these info. with WMI you can retrieve these data through Win32_LogonSession and Win32_LoggedOnUser and extract start time from them. with subtracting from DateTime.Now you'll have the duration it would be somewhat like this

        class UserLogonData
        {
            const string ALLUSERS = "All";
        
            readonly string userName;
            readonly DateTime loggedOnTime;
            string logonId;
        
            public string UserName
            {
                get { return this.userName; }
            }
            public DateTime LoggedOnTime
            {
                get { return this.loggedOnTime; }
            }
            public string LogonID
            {
                get { return this.logonId; }
            }
            public TimeSpan LoggedDuration
            {
                get { return DateTime.Now.Subtract(this.loggedOnTime); }
            }
        
            private UserLogonData(string userName, string logonId, DateTime loggedOnTime)
            {
                this.userName = userName;
                this.logonId = logonId;
                this.loggedOnTime = loggedOnTime;
            }
        
            public override string ToString()
            {
                return this.userName;
            }
        
            public static UserLogonData\[\] GetUsersLogonTime(string userName)
            {
                List dataList = new List();
        
                ManagementObjectSearcher mosUser = new ManagementObjectSearcher(new SelectQuery("Win32\_LoggedOnUser"));
                ManagementObjectSearcher mosSession = new ManagementObjectSearcher(new SelectQuery("Win32\_LogonSession"));
        
                ManagementObjectCollection mocUser = mosUser.Get();
                ManagementObjectCollection mocSession = mosSession.Get();
        
                foreach (ManagementObject moUser in mocUser)
                {
                    string userLogonAntecedentData = moUser.Properties\["Antecedent"\].Value.ToString();
                    string userLogonUserName = Regex.Replace(userLogonAntecedentData, @".\*Name=""(?'name'.+)"".\*", "${name}");
                    if (userName!=ALLUSERS && userLogonUserName != userName) continue;
                    string userLogonDependentData = moUser.Properties\["Dependent"\].Value.ToString();
                    string userLogonSessionId = Regex.Replace(userLogonDependentData, @".\*LogonId=""(?'id'\\d+)"".\*", "${id}");
                    foreach (ManagementObject moSession in mocSession)
                    {
        
        L Offline
        L Offline
        Lutoslaw
        wrote on last edited by
        #3

        Thank you, thank you and thank you! 1 ) What about this situation:

        (current user time line)
        SYSTEM START>------|------------|--------|----------|------->NOW
        user A|user B |user C |user B |user A
        where "|" is a logout/switch operation.

        And I want to calculate how long the user A used computer. Your Duration property calculates duration assuming that all these users are STILL logged in. I suppose a property "LogOutTime" would do that. 2 ) How do you know that?? Please post some knowledge source - I couldn't find it anywhere.

        Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

        H 1 Reply Last reply
        0
        • L Lutoslaw

          Thank you, thank you and thank you! 1 ) What about this situation:

          (current user time line)
          SYSTEM START>------|------------|--------|----------|------->NOW
          user A|user B |user C |user B |user A
          where "|" is a logout/switch operation.

          And I want to calculate how long the user A used computer. Your Duration property calculates duration assuming that all these users are STILL logged in. I suppose a property "LogOutTime" would do that. 2 ) How do you know that?? Please post some knowledge source - I couldn't find it anywhere.

          Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

          H Offline
          H Offline
          Hessam Jalali
          wrote on last edited by
          #4

          unfortunately it seems there is no LogOutTime property (at least I didn't found out anyOne) but AFAIK In windows only on user can work at the same time so there is a class in .NET name Microsoft.Win32.SystemEvents.SessionEnding it happens when a user trying to logoff or shutdown so you can find active user through WMI again or through System.Environment.UserName and find you are in which session. I think with adding the event to the class you can find total duration.(but it needs your program always run or atleaset when user is going to logout or shutdown) if you get the duration inside the method associated with that event it would be total user log time. ofcourse there is another approaches like looking inside eventlogs but i think this is the easiest one hope the post would be useful

          L 1 Reply Last reply
          0
          • H Hessam Jalali

            unfortunately it seems there is no LogOutTime property (at least I didn't found out anyOne) but AFAIK In windows only on user can work at the same time so there is a class in .NET name Microsoft.Win32.SystemEvents.SessionEnding it happens when a user trying to logoff or shutdown so you can find active user through WMI again or through System.Environment.UserName and find you are in which session. I think with adding the event to the class you can find total duration.(but it needs your program always run or atleaset when user is going to logout or shutdown) if you get the duration inside the method associated with that event it would be total user log time. ofcourse there is another approaches like looking inside eventlogs but i think this is the easiest one hope the post would be useful

            L Offline
            L Offline
            Lutoslaw
            wrote on last edited by
            #5

            Thanks! However it seems to be difficult to get a real duration because of Windows hibernate service. UserLogonData.GetUsersLogonTime(Environment.UserName) returns an array which contains two items. NOW it looks like I'm sitting on this chair for LoggedDuration {1.04:01:07} - from yesterday evening, when Windows was hibernated (28 hours?? Oh God...). or LoggedDuration {01:49:33.6101250} - today (almost two hours, not so bad) ? "AFAIK In windows only on user can work at the same time": Yes, but more than one may be logged in at the same time AND one user can work more than one time in the single system session (if e.g. some other guy kicked him out for a while because he "just wanted to check mailbox", but after that that guy could return back -- and I want to know how (totally) this first guy was sitting on the chair).

            Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

            H 1 Reply Last reply
            0
            • L Lutoslaw

              Thanks! However it seems to be difficult to get a real duration because of Windows hibernate service. UserLogonData.GetUsersLogonTime(Environment.UserName) returns an array which contains two items. NOW it looks like I'm sitting on this chair for LoggedDuration {1.04:01:07} - from yesterday evening, when Windows was hibernated (28 hours?? Oh God...). or LoggedDuration {01:49:33.6101250} - today (almost two hours, not so bad) ? "AFAIK In windows only on user can work at the same time": Yes, but more than one may be logged in at the same time AND one user can work more than one time in the single system session (if e.g. some other guy kicked him out for a while because he "just wanted to check mailbox", but after that that guy could return back -- and I want to know how (totally) this first guy was sitting on the chair).

              Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

              H Offline
              H Offline
              Hessam Jalali
              wrote on last edited by
              #6

              first sorry for delay I was in vacation :) yes you're right it cannot be done as straight as a simple win App but with services you can, and writing services in .NET is not harder than writing simple winApp it can be done with services because they'll works even when a user switch or logoff. and I think you must log some data byyourself if you need accurate times (like finding hibernate time and subtract it and ...)

              gajatko wrote:

              if e.g. some other guy kicked him out for a while because he "just wanted to check mailbox", but after that that guy could return back

              there is another event in SystemEvents Class name SessionSwitch it will occur when the user going to change so I think UserSwitch would be included and when you hibernate it seems something like userSwitch happens (but I'm not sure) so maybe this event would be useful.

              gajatko wrote:

              from yesterday evening, when Windows was hibernated (28 hours?? Oh God...).

              another event is PowerModeChanged which will return your computer is going to suspend mode or not and hibernate is counted as a suspend mode (atleast in .NET)this event may help to retrieve hibernate status too. and at last I think you can retrieve some data from the Service status (like Puase/Stop) and use it for finding machine state like shutdown hibernate good luck :)

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups