0

How would I execute code in a C# application when a process (of any type) is launched on the system?

For example, if I started notepad.exe - I would be able to get the path, "C:\Windows\notepad.exe".

Tom W
  • 19
  • 1
  • 5
  • Please explain more with an Example to make it Clear. – Sayed Muhammad Idrees Dec 19 '19 at 17:59
  • You mean like a Virus scanner scanning the file before Execution? Or something like logging each and every programm start, even if they do not log anything? | This sounds a lot like a XY Problem so a complete picture would help. – Christopher Dec 19 '19 at 18:02
  • If you're interested just in windowed processes, you could use UI Automation. Something like [this](https://stackoverflow.com/a/55960110/7444103) (it talks about *Forms*, but it will detect the creation of any Window type, console included). If you're interested in the creation of any process type, you can use a [ManagementEventWatcher](https://learn.microsoft.com/en-us/dotnet/api/system.management.managementeventwatcher), something like [this](https://stackoverflow.com/a/54298316/7444103) (of course, the WMI class will be `Win32_Process`, not `Win32_DiskDrive` as shown there) – Jimi Dec 19 '19 at 18:13
  • Your question is ambiguous. You said *Is there a way to run code when any process is launched on the system in c#?" Do you mean you want code, written in C#, that will run whenever a process is started? Or do you mean you want code that will run whenever a C# process is started? – Jim Mischel Dec 19 '19 at 18:48

1 Answers1

1

Not in managed code no - you can invoke into the Win32 API using something like:

Hook ZwCreateSection(), CreateProcess() and CreateProcessEx() using mhook to block certain application from launching or

https://www.codeproject.com/articles/11985/hooking-the-native-api-and-controlling-process-cre

technically from C#, but your going to have to use windows api functions as there is no .Net equivalent.

You can however iterate currently running processes using the Process class, so if you don't care about missing short-lived processes you could just do that on a timer?

Milney
  • 6,253
  • 2
  • 19
  • 33