2

Situation:

  1. I spawn processes for various file types (pictures, Word documents, etc) by relying on the default associated handler program. This means that I only specify the particular file name as the StartInfo.FileName, and no actual executable precedes that file name. At the same time I specify StartInfo.UseShellExecute = true. This way the associated software with that file type will start.
  2. My goal is to get notified when that process exits.


Process process = new Process();
try
{
    process.StartInfo.UseShellExecute = true;
    process.StartInfo.FileName = pFullPath;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.RedirectStandardError = true;
    bool notReused = process.Start();
}
catch (Win32Exception ex)

Variations:

  • Process's static Start method does return a Process, but I get back null/empty object for my scenario. So that's why I instantiate a Process class explicitly, set parameters for its StartInfo property, and then call non-static Start() in the end, so I have a hold of that Process object instance.
  • If I say StartInfo.UseShellExecute = false, I get an exception, 'cause I didn't specify executable name. It seems that that's the way to invoke associated program with a file type.
  • The non-static Process.Start has a boolean return value, and it indicates that the system reused a Process. I don't want that, but I don't know how to avoid it.
  • I tried to set Redirect* booleans of StartInfo, but that throws the InvalidOperationException again, and that conforms to the documentation.

If I had a "good" Process object, I could hook up the Exited handler and set EnableRaisingEvents to true. I'm amazed and sad how such a PITA is this.

Csaba Toth
  • 10,021
  • 5
  • 75
  • 121
  • 4
    What you're asking for is actually completely impossible. http://blogs.msdn.com/b/oldnewthing/archive/2006/05/05/590749.aspx – SLaks Dec 27 '12 at 18:05
  • Thanks SLaks, I thought that deep inside my soul, but I never give up. Raymond Chen rocks, I have his blog compilation book. I already have concept code using FileSystemWatcher since I control the file itself. I should probably go down that road. – Csaba Toth Dec 27 '12 at 18:42
  • I want to mark SLaks's answer as correct, but it is only a comment. Can a moderator convert it to an answer? – Csaba Toth Apr 02 '13 at 00:43
  • Actually, moderators cannot do that. – SLaks Apr 03 '13 at 03:26

1 Answers1

2

This is completely impossible.
Launching a file is not guaranteed to create a process at all.

Raymond Chen has far more detail.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964