Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monitor process/program execution in windows?

We are trying to develop a small application that can monitor the programs/processes that are executing in a windows machine.

If the program/process is not supposed to run, it should be blocked. It works similar to an antivirus.

This is the basic idea.

I want to know the ways to hook into the OS to get notified about every single program/process trying to run in the machine.

like image 615
Niyaz Avatar asked Feb 04 '09 07:02

Niyaz


People also ask

How do I monitor a process in Windows?

All operating systems include a utility that shows current processes. In Windows, this utility is the Task Manager. To get it, right-click on the Taskbar and select Task Manager from the pop-up menu that appears. This utility list all processes in categories.


1 Answers

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.

like image 169
Rob Haupt Avatar answered Oct 13 '22 00:10

Rob Haupt