Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a process start & end using c# in windows?

I have a good working experience with C# but now I want to develop a simple(may be a console app) software which just detects the name and time of the process started or ended on my computer.

For example (I am assuming that my small app is already running) if a user opens Firefox then it should just insert firefox.exe into a database with time and if a user close it then it also do the same.

And same as above if a user open notepad then it should insert notepad.exe with time and so on.

I know how to insert values in database but I just need your help in identifying when the process/program starts or ends on my system.

Honestly saying I never developed this kind of application before so i have no idea that it can be possible using console app or i need to make a windows service app etc.

So please provide your answer just considering me as a beginner.

In the part of C# I am able to understand it so need to worry about that.

I am using visual studio 2010 with .net 4.0.

like image 324
Peeyush Avatar asked Dec 10 '11 10:12

Peeyush


People also ask

How can I tell when Windows process started?

Open Task Manager and right-click on the process. Choose Properties in the menu and look at the field Accessed in the first tab. Unless multiple instances have been started this will give you the start time of the process. Show activity on this post.

What is process start?

Start(ProcessStartInfo)Starts the process resource that is specified by the parameter containing process start information (for example, the file name of the process to start) and associates the resource with a new Process component.

How can you tell if a process is completed in C#?

If it's a quick process, just wait for it. process. WaitForExit(); If you're starting one up in the background, subscribe to the Exited event after setting EnableRaisingEvents to true.

How do I see what processes are running in Windows?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column.


1 Answers

To do this without polling requires WMI. This is well supported in .net and you can use the ManagementEventWatcher class to subscribe to WMI notifications.

This Code Project article illustrates how it is done. Here's an extract showing how straightforward it is.

notePad = new ProcessInfo("notepad.exe");
notePad.Started +=
    new Win32Process.ProcessInfo.StartedEventHandler(this.NotepadStarted);
notePad.Terminated +=
    new Win32Process.ProcessInfo.TerminatedEventHandler(this.NotepadTerminated);

Note that ProcessInfo is a class implemented in the code attached to that article.

like image 147
David Heffernan Avatar answered Oct 11 '22 02:10

David Heffernan