views:

89

answers:

1

I would like to have some eventhandler which raise if a new application is started. I've heard that this is possible by using a hook but the only examples I can find are based on mouse/keyboard events.

What is an example link of how I can create such a hook in C#?

Oh and btw: Nope, I don't want to use WMI which could be a solution as well but it's not an option in my case.

A: 

You can use a far from elegant solution which is perform a polling to the processes in the system.

Process[] currentProcessList = Process.GetProcesses();

List<Process> newlyAddedProcesses = new List<Process>();
while (true)
{
    newlyAddedProcesses.Clear();
    Process[] newProcessList = Process.GetProcesses();

    foreach (Process p in newProcessList)
    {
        if (!currentProcessList.Contains(p))
        {
            newlyAddedProcesses.Add(p);
        }
    }

    //TODO: do your work with newlyAddedProcesses

    System.Threading.Thread.Sleep(500);
    currentProcessList = newProcessList;
}

If your application doesn't need a high accuracy you can setup a big sleep time between polls which would make it much less time consuming.

Cristian
This way I have to loop through all processes again and again and again. At the moment my application does work on a timer based way but I do not want to use a timer since there is a way to get to the real events. Timer based solutions are something like a waste of time and performance. But thanks anyway! :)
Marcus