Hi all,

I want to make a program that monitors a certain process by its name given by the user.

So the program starts at computer start up and asks you the name of the process that you want it to monitor( e.x. "nfsw.exe" or "klimn.exe" or etc.) then after 3 hours you start the process "klimn.exe".

I want the program to monitor all proceses until you start the klimn.exe process and then keep track of how much time you spent in that process, and writes that time in a file, after you closed the file.

The thing is that i don't know nothing about process monitoring, i looked on the web i found some like process audit but a friend of mine told me that there is a way easier way to do that.

My question is what do i have to look for?I only need indications, link, etc.I want to do this by my own.

Dani AI

Generated

Quick diagnosis for : the code never hits the write path because it compares the wrong property. StartInfo.FileName is only meaningful for processes started via a ProcessStartInfo created by the same process; for existing system processes that property is normally empty, so the equality test always fails. was on the right track suggesting to match on the actual process name, and ’s suggestion to go event-driven is useful for efficiency.

A practical, robust approach:

  • Normalize the target (accept "klimn" or "klimn.exe" and compare case-insensitively).
  • Maintain a map keyed by PID that stores when each matching process was first seen.
  • When a PID disappears (or when an exit event fires), compute elapsed = stop - start and append a CSV row (process, PID, start, stop, seconds). This handles multiple instances and lets durations be accumulated per run.
  • Use try/catch around reads like StartTime, MainModule.FileName or TotalProcessorTime (they can throw or require elevation). Decide whether “time spent” means wall-clock (Start/Stop) or CPU usage (TotalProcessorTime).
  • For low overhead on Windows, prefer event-based detection (WMI/ETW) instead of tight polling; run the monitor as a background service if it must survive logouts.

Example (Python + psutil) that shows the PID-tracking pattern and appends durations to CSV:

import time, os, csv, psutil

target = "klimn.exe"
base = os.path.splitext(target.lower())[0]
tracked = {}   # pid -> start_time
out = r"C:\Users\P4\Desktop\test.csv"

def append_record(name, pid, start, stop):
    with open(out, "a", newline="") as f:
        csv.writer(f).writerow([name, pid, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start)),
                                time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stop)), round(stop-start,2)])

while True:
    for p in psutil.process_iter(['pid','name','create_time']):
        try:
            n = p.info['name']
            if n and os.path.splitext(n.lower())[0] == base and p.info['pid'] not in tracked:
                tracked[p.info['pid']] = p.info.get('create_time', time.time())
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pass
    for pid in list(tracked):
        if not psutil.pid_exists(pid):
            s = tracked.pop(pid); append_record(target, pid, s, time.time())
    time.sleep(1)

Troubleshooting notes: log observed process names/PIDs to confirm matches, verify the output path and permissions, test with a simple target like notepad.exe, and avoid relying on StartInfo for externally-started processes.

Recommended Answers

All 4 Replies

My question is what do i have to look for?I only need indications, link, etc.I want to do this by my own.

Google for Windows Management Instrumentation (WMI)

I've gone this far but it seems that it doesnt write in the file,can please someone tell me why!

public Form1()
        {
            InitializeComponent();
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new System.Timers.ElapsedEventHandler(aTimer_Elapsed);
            aTimer.Interval = 30000;
            aTimer.Enabled = true;
            MessageBox.Show("Aveti 30 de secunde sa scrieti numele procesului");
        }

        System.Timers.Timer aTimer;
        StreamWriter writeTest;
        Process[] runningProcess;

        void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            runningProcess = Process.GetProcesses();
                foreach (Process proc in runningProcess)
                {
                    if (proc.StartInfo.FileName == txtBoxProcess.Text)
                    {
                        writeTest = new StreamWriter(@"C:\Users\P4\Desktop\test.txt");
                        string temp = Convert.ToString(proc.StartTime.DayOfYear);
                        writeTest.WriteLine(temp);
                        writeTest.Close();
                    }
                }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            aTimer.Stop();

        }

You may also need performance counter

      processlist = Process.GetProcesses();
        cpuCounter = new PerformanceCounter();

The following will give you CPU usage at anytime
cpuCounter.CategoryName = "Process"; // Processor
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "Idle"; // "_Total";

To check for a specific process use

        foreach (Process aprocess in processlist)
        {
              if (aprocess.ProcessName.ToLower() == userprocessvar)

                  // code
          }

It is all in

            using System.Management;
            using System.Diagnostics;

it seems that it doesnt write in the file,can please someone tell me why!

I'll take a guess at this one.

    if (proc.StartInfo.FileName == txtBoxProcess.Text)


I believe the equality operator above needs an exact case sesnistive comparison of the two strings.  Thus, the strings must match perfectly so that the resultant Boolean value is true.

It might be that you're entering Svchost in your textbox but the actually name of the process is svchost. Notice the case difference in the two names which would mean that they do not match in case sesnitivity.  Therefore, you won't be able to write to the textfile.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.