How to calculate the total time a user spending on an application?

后端 未结 6 1040
Happy的楠姐
Happy的楠姐 2021-02-07 08:16

I want to create an application that able to calculate the total time the user (i.e. myself) spent on a particular application, for example Firefox. And this application should

6条回答
  •  灰色年华
    2021-02-07 08:44

    Here is almost the entire source for a WinForms app that does this. Note that it only adds time when Firefox has focus.

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    
    namespace FireFoxWatch
    {
      public partial class Form1 : Form
      {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
    
        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
    
        private TimeSpan fireFoxElapsedTime = new TimeSpan();
    
        public Form1()
        {
          InitializeComponent();
        }
    
        // this handler is called each time the Timer component's interval is reached.
        private void timer1_Tick(object sender, EventArgs e)
        {
          var wnd = GetForegroundWindow();
          uint procId;
          GetWindowThreadProcessId(wnd, out procId);
    
          var process = Process.GetProcessById((int)procId);
          if (process.ProcessName.Equals("firefox", StringComparison.CurrentCultureIgnoreCase))
            fireFoxElapsedTime += new TimeSpan(0, 0, 0, 0, timer1.Interval);
    
          //TODO: If fireFoxElapsedTime > Some predetermined TimeSpan, play a sound.
          // Right now it just updates a display label.
          label1.Text = fireFoxElapsedTime.ToString();
        }
    
        // start the timer when the form loads.
        private void Form1_Load(object sender, EventArgs e)
        {
          timer1.Start();
        }
      }
    }
    

    The only part not shown here, is that I made a default WinForms app, then added a "Timer" component from the toolbox, which is named "timer1" in the code, and was the default name.

    The above code just updates the total time on a winform label, but you could easily add code to play a sound.

提交回复
热议问题