1

In my C# Winforms application I implemented a watcher that notify me when a new process starts in the local OS.

ManagementEventWatcher watcher = new ManagementEventWatcher(new ManagementScope("\\\\.\\root\\cimv2"), new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 0, 1), "TargetInstance ISA 'Win32_Process'"));
watcher.Scope.Options.EnablePrivileges = true;
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);

I'm not directly interested in the process started but in an eventual file that caused the process to start. Think about a double click on "d:\documents\doc.txt" that causes notepad.exe to be launched. The watcher notifies me about the new notepad.exe process and then I can check if there is a file responsible for its starting.

This is the code that notifies me when the event arrives.

void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
  ManagementBaseObject mbo = (ManagementBaseObject)e.NewEvent["TargetInstance"];
  string executable = mbo.GetPropertyValue("ExecutablePath").ToString().ToLower();
  string commandLine = mbo.GetPropertyValue("CommandLine").ToString().ToLower();
  [...]
}

Inside the variable commandLine I find the full command line, in my example:

c:\windows\system32\notepad.exe d:\documents\doc.txt

The code works well for almost every program but I found a problem with files whose extensions are linked with no program. When I double click on one of this file the Open With dialog (the process name is openwith.exe) pops up and I am regularly notified by the watcher but when I read the CommandLine property I found something like this:

c:\windows\system32\openwith.exe -embedding

instead of the expected:

c:\windows\system32\openwith.exe d:\documents\document.unlinkedExt

All the properties I can analize from the mbo oject don't help me. My assumption is that this kind of instance is not using an usual command line to execute the process.

The question is: how can I extract the full file path that caused the Open With dialog opening?

Checked on Windows 8.1 and 10 with .NET framework 2.0 and 4.0.

epikarma
  • 41
  • 1
  • 7

0 Answers0