Pages

Friday, July 6, 2012

How to monitor process/program execution in windows

The easiest way is to use WMI. Specifically monitor the Win32_ProcessStartTrace. This is better than Win32_Process, because it is setup to use events whereas Win32_Process requires polling which is more CPU intensive. Below is how to do it in C#. First make sure that System.Management is setup as a reference for your project



public System.Management.ManagementEventWatcher mgmtWtch;

    public Form1()
    {
        InitializeComponent();
        mgmtWtch = new System.Management.ManagementEventWatcher("Select * From Win32_ProcessStartTrace");
        mgmtWtch.EventArrived += new System.Management.EventArrivedEventHandler(mgmtWtch_EventArrived);
        mgmtWtch.Start();
    }

    void mgmtWtch_EventArrived(object sender, System.Management.EventArrivedEventArgs e)
    {
        MessageBox.Show((string)e.NewEvent["ProcessName"]);
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        mgmtWtch.Stop();
    }


The code will generate a messagebox everytime you launch a new process. From there you can check a whitelist/blacklist and act appropriately.

No comments:

Post a Comment