Terminate a Process - CSharp Operating System

CSharp examples for Operating System:Process

Description

Terminate a Process

Demo Code


using System;/*  w w  w  .  ja v a  2s.  co  m*/
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();
                    }
                }
            }
        }
    }

Result


Related Tutorials