15

Is there any event when a new process is created. I'm writing a c# application that checks for certain processes, but I don't want to write an infinite loop to iterate through all known processes continuously. Instead, I rather check each process that is created or iterate through all current processes triggered by an event. Any suggestions?

        Process[] pArray;
        while (true)
        {
            pArray = Process.GetProcesses();

            foreach (Process p in pArray)
            {
                foreach (String pName in listOfProcesses)  //just a list of process names to search for
                {

                    if (pName.Equals(p.ProcessName, StringComparison.CurrentCultureIgnoreCase))
                    {
                       //do some stuff

                    }
                }
            }

            Thread.Sleep(refreshRate * 1000);
        }
Kevin
  • 589
  • 5
  • 15

1 Answers1

21

WMI gives you a means to listen for process creation (and about a million other things). See my answer here.

 void WaitForProcess()
{
    ManagementEventWatcher startWatch = new ManagementEventWatcher(
      new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
    startWatch.EventArrived
                        += new EventArrivedEventHandler(startWatch_EventArrived);
    startWatch.Start();
}

static void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
    Console.WriteLine("Process started: {0}"
                      , e.NewEvent.Properties["ProcessName"].Value);
    if (this is the process I'm interested in)
    {
             startWatch.Stop();
    }
}
Community
  • 1
  • 1
Michael Petrotta
  • 58,479
  • 27
  • 141
  • 176
  • 4
    Listening for this event requires administrative access. If using Visual Studio, you can simply run Visual Studio as administrator to also debug the application as admin. – Albert MN. May 14 '18 at 19:13
  • 1
    Is there a non elevated solution? – Wobbles Jun 21 '18 at 18:55