Sunday, June 5, 2011

Watch For Process Start using C#

I wanted to write a console application, that will watch the system and trigger an event when a new process has started. So did some coding using ManagementEventWatcher Class which comes under System.Management namespace.

I am going to post down the code, but since this can be used to do unethical things like creating a simple virus, I will only write down the two most important methods.

// this method will capture every process start
public static void MonitorForProcessToStart()
{
      // create event query to be notified within 1 second of a change in a service
     WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1),
          "TargetInstance isa \"Win32_Process\"");

      ManagementEventWatcher watcher = new ManagementEventWatcher();
      watcher.Query = query;
      watcher.EventArrived += new EventArrivedEventHandler(ProcessStartEvent);
      watcher.Start();
}

In Here TimeSpan is a timespan value specifying the latency acceptable for receiving this event. This value is used in cases where there is no explicit event provider for the query requested, and WMI is required to poll for the condition. This interval is the maximum amount of time that can pass before notification of an event must be delivered.

// when a new process has started, it will trigger this event
public static void ProcessStartEvent(object sender, EventArrivedEventArgs e)
{
      // when this method has triggered a new process has started.
      // in here you can do what ever you want.
}

Using these two methods, there is a lot a good programmer can do. Not to mention you can do unethical things too. So I will not go deeper about the things you can do.

Feel free to give me your feedback.

Happy Coding.

Regards,
Jaliya

4 comments:

  1. "this can be used to do unethical things" - WTF?!

    That's true of any knowledge. Why even bother hinting at it?

    ReplyDelete
  2. Nice article. Thanks

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete