I want to write for myself a simple service to keep track of what programs I work with during the day and how much time I spend on them.

How do I imagine the work of such a program? I have a program running on my PC in the background that will monitor the current active window and how active it is. The following data will be sent to the server:

Процесс Был активен phpstrom.exe 3600 

Well, then this data will be displayed in the form of graphs.

The question is - is it possible to implement this in C #? Unfortunately, I have no experience developing software for Windows, so I have no idea what I need to use. Could you suggest a technology and an example of how you can get the process name of the current active window?

    2 answers 2

    What you want can be done using winapi functions. You will need two: GetForegroundWindow , GetWindowThreadProcessId

    Using the links, you can find a description of the parameters of the functions and in which DLL library they are located. Their description must be declared in c # as follows:

      [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern UInt32 GetWindowThreadProcessId(IntPtr hwnd, ref Int32 pid); 

    After that they can be used. The first function gets the handle of the active window, the second gets the process ID by the window handle. In the System.Diagnostics space there is a Process class with which you can get data about the process. Well, at least the title of the window. Here is an example of use:

     IntPtr h = GetForegroundWindow(); int pid = 0; GetWindowThreadProcessId(h, ref pid); Process p = Process.GetProcessById(pid); Console.Write("pid: {0}; window: {1}", pid, p.MainWindowTitle); 

      Specifically, I did not solve this problem, but apparently you need:
      GetForegroundWindow() - to get the handle of the active window;
      GetWindowThreadProcessId() - to get the PID by the handle;
      GetProcessImageFileName() - to get the binary name of the process handle.

      • Thank you, now I will try =) - Ilya Bizunov