Monitor when an exe is launched

前端 未结 5 1701
一生所求
一生所求 2020-12-04 15:43

I have some services that an application needs running in order for some of the app\'s features to work. I would like to enable the option to only start the external Window

5条回答
  •  温柔的废话
    2020-12-04 16:36

    From this article, you can use WMI (the System.Management namespace) in your service to watch for process start events.

     void WaitForProcess()
    {
        ManagementEventWatcher startWatch = new ManagementEventWatcher(
          new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
        startWatch.EventArrived
                            += new EventArrivedEventHandler(startWatch_EventArrived);
        startWatch.Start();
    
        ManagementEventWatcher stopWatch = new ManagementEventWatcher(
          new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
        stopWatch.EventArrived
                            += new EventArrivedEventHandler(stopWatch_EventArrived);
        stopWatch.Start();
    }
    
      static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) {
        stopWatch.Stop();
        Console.WriteLine("Process stopped: {0}"
                          , e.NewEvent.Properties["ProcessName"].Value);
      }
    
      static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) {
        startWatch.Stop();
        Console.WriteLine("Process started: {0}"
                          , e.NewEvent.Properties["ProcessName"].Value);
      }
    }
    

    WMI allows for fairly sophisticated queries; you can modify the queries here to trigger your event handler only when your watched app launches, or on other criteria. Here's a quick introduction, from a C# perspective.

提交回复
热议问题