Detecting Process Completion


   
 
using System;
using System.Diagnostics;

public class DetectingProcessCompletion
{
    static void ProcessDone(object sender, EventArgs e)
    {
        Console.WriteLine("Process Exited");
    }
    
    public static void Main()
    {
        Process p = new Process();
        p.StartInfo.FileName = "notepad.exe";
        p.StartInfo.Arguments = "process3.cs";
        p.EnableRaisingEvents = true;
        p.Exited += new EventHandler(ProcessDone);
        p.Start();
        p.WaitForExit();
        Console.WriteLine("Back from WaitForExit()");
    }
}
           
         
     


Enum Modules For Pid

   
  

using System;
using System.Diagnostics;

class MainClass {
    static void Main(string[] args) {
        int pID = 12345;
        Process theProc;
        try { theProc = Process.GetProcessById(pID); } catch {
            Console.WriteLine("bad PID!");
            return;
        }
        Console.WriteLine("Here are the loaded modules for: {0}", theProc.ProcessName);
        try {
            ProcessModuleCollection theMods = theProc.Modules;
            foreach (ProcessModule pm in theMods) {
                Console.WriteLine(string.Format("-> Mod Name: {0}", pm.ModuleName));
            }
        } catch { Console.WriteLine("No mods!"); }

    }
}

   
     


CloseMainWindow,WaitForExit

   
  


using System;
using System.Threading;
using System.Diagnostics;

class MainClass
{
    public static void Main()
    {
        using (Process process = Process.Start("notepad.exe", @"c:SomeFile.txt"))
        {
            Console.WriteLine("Waiting 5 seconds before terminating notepad.exe.");
            Thread.Sleep(5000);
            Console.WriteLine("Terminating Notepad with CloseMainWindow.");
            if (!process.CloseMainWindow())
            {
                Console.WriteLine("CloseMainWindow returned false - " + " terminating Notepad with Kill.");
                process.Kill();
            }
            else
            {
                if (!process.WaitForExit(2000))
                {
                    Console.WriteLine("CloseMainWindow failed to" + " terminate - terminating Notepad with Kill.");
                    process.Kill();
                }
            }
        }
    }
}

   
     


Start And Kill Process

   
  

using System;
using System.Diagnostics;

class MyProcessManipulator {
    static void Main(string[] args) {
        Process ieProc = Process.Start("IExplore.exe", "www.intertechtraining.com");

        Console.Write("--> Hit a key to kill {0}...", ieProc.ProcessName);
        try {
            ieProc.Kill();
        } catch { } // In case user already killed it...

    }
}