Share via

C# Windows form application that records time spent on all application

harsha111111 121 Reputation points
2021-07-02T10:11:08.12+00:00

I have code for firefox that shows how much time I spent in it when it is active window

[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();

    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);
             }
        label2.Text = fireFoxElapsedTime.ToString();
    }

I need for all the applications whichever is active and data should be stored in sqlite

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Castorix31 91,871 Reputation points
2021-07-02T13:35:36.813+00:00

You can use the same code by storing in a List or array the process names from GetForegroundWindow
If the process exists in the List, you add the time for this process, if not, you add the process name in the List then add the time

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.