How to determine when a shelled process ends in Visual C# (304032)



The information in this article applies to:

  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET (2002)

This article was previously published under Q304032
For a Microsoft Visual Basic .NET version of this article, see 306394.
For a Microsoft Visual C++ .NET version of this article, see 307011.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
  • System.Diagnostics

IN THIS TASK

SUMMARY

This step-by-step article shows you how to use the Process object to start another process and receive a notification after that process has exited. The Process object, which is located in the System.Diagnostics namespace, exposes the Exited event. By handling this event, you are notified when the process that you launch has exited. Because you are using an event to accomplish this task, this notification process is asynchronous.

back to the top

Requirements

  • Visual Studio .NET or Visual Studio 2005
  • Visual C# Language Compiler
back to the top

Create the Sample

  1. Create a new Visual C# .NET Windows Application project or a new Visual C# 2005 Windows Application project. Form1 is created by default.
  2. Double-click Form1, and add the following code to the Form1 Load event handler:
    p = new System.Diagnostics.Process();
    // Handle the Exited event that the Process class fires.
    this.p.Exited += new System.EventHandler(this.p_Exited);
    p.EnableRaisingEvents = true;
    p.SynchronizingObject = this;
    p.StartInfo.FileName = "notepad.exe";
    p.Start(); 
    					
  3. Below the Form1_Load method, add another method that will handle the Exited event:
    private void p_Exited(object sender, System.EventArgs e)
    {
       MessageBox.Show("Notepad was closed");
    }
    					
  4. Add the following declaration to the Form1 class to declare your process variable:
        private System.Diagnostics.Process p;
    					
  5. Press F5 to run the application. The application should start, along with an instance of Notepad.
  6. Close Notepad. Note that the Exited event fires, which causes a message box to appear.
back to the top

Modification Type:MinorLast Reviewed:10/4/2006
Keywords:kbHOWTOmaster KB304032 kbAudDeveloper