You are currently offline, waiting for your internet to reconnect

How to use Visual C# to close another application

This article was previously published under Q305603
For a Microsoft Visual Basic .NET version of this article, see 305602.

For a Microsoft Visual C++ .NET version of this article, see 307395.

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


This step-by-step article shows you how to close an application from within an application. It also describes how to close a specific instance of another application, such as Notepad, if more than one instance of the application is running.

back to the top

Discussion of the Programming Logic

Declare Variables

Several variables must be defined. Because these variables are used in multiple methods, they should be defined outside of any procedure so that they remain in scope. The first variable is an array that holds the process objects that are returned by the GetProcessByName method, and the string variable that is used to hold the name of the process is procName:
private Process[] processes;private string procName = "Notepad";				

Obtain a List of Application Instances

The following code comprises a function (called buildList in the sample) that is called each time a new instance of Notepad is created. This sample stores the process information in a ListView control; the code to populate the ListView control is included only for consistency with the complete sample. The most important part of this code is the call to the GetProcessByName method of the Process class. This method returns an array of Process objects, which can be iterated through a For...Each block:
ListViewItem itemAdd ; ListView1.Items.Clear();processes = Process.GetProcessesByName(procName);foreach (Process proc in processes)    {        itemAdd = ListView1.Items.Add(proc.MainWindowTitle);        itemAdd.SubItems.Add(proc.Id.ToString());    }				

Close a Specific Instance of an Application

When multiple instances of an application are running, and you want to close one instance, you must differentiate between those processes. The following sample uses the Id property of the Process object to tell the processes apart. The Id property and the MainWindowTitle property (another property of the Process object) are stored in the ListView control. The code obtains the item that is currently selected in the ListView control, obtains a reference to the process by using the GetProcessById method of the Process class, and closes that process by calling the CloseMainWindow method:
try{         	int procID=System.Convert.ToInt32(ListView1.SelectedItems[0].SubItems[1].Text);	Process tempProc=Process.GetProcessById(procID);	tempProc.CloseMainWindow();	tempProc.WaitForExit();	buildList();}catch{	MessageBox.Show("Please select a process in the ListView before clicking this button." +		" Or the Process may have been closed by somebody." );	buildList();}				

Close All Instances of an Application

Closing all instances of a particular application is relatively straightforward. You can walk the array that is returned by the GetProcessByName method and call the CloseMainWindow method on each process object, as follows:
try{	foreach (Process proc in processes)	{		proc.CloseMainWindow();		proc.WaitForExit();	}	buildList();}catch (System.NullReferenceException){	MessageBox.Show("No instances of Notepad running.");}				
back to the top

Steps to Build the Sample

  1. Start a new Visual C# Windows application in Visual Studio .NET.
  2. Right-click the default form, Form1.cs, and select View Code.
  3. Replace the code that is in the code window with the following:
    using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;using System.Diagnostics;namespace closeApplication_cs{	/// <summary>	/// Summary description for Form1.	/// </summary>	public class Form1 : System.Windows.Forms.Form	{		internal System.Windows.Forms.Button btnCloseAll;		internal System.Windows.Forms.ColumnHeader ColumnHeader2;		internal System.Windows.Forms.ColumnHeader ColumnHeader1;		internal System.Windows.Forms.Button btnLaunch1;		internal System.Windows.Forms.ListView ListView1;		internal System.Windows.Forms.Button btnClose1;		/// <summary>		/// Required designer variable.		/// </summary>		private System.ComponentModel.Container components = null;		private Process[] processes;		private string procName = "Notepad";		private string specialFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.System);		public Form1()		{			// 			// Required for Windows Form Designer support.			// 			InitializeComponent();			// 			// To do: Add any constructor code after the InitializeComponent call.			// 		}		/// <summary>		/// Clean up any resources that are being used.		/// </summary>		protected override void Dispose( bool disposing )		{			if( disposing )			{				if (components != null) 				{					components.Dispose();				}			}			base.Dispose( disposing );		}    #region Windows Form Designer generated code		/// <summary>		/// Required method for Designer support - do not modify		/// the contents of this method with the code editor.		/// </summary>		private void InitializeComponent()		{			this.btnClose1 = new System.Windows.Forms.Button();			this.ColumnHeader2 = new System.Windows.Forms.ColumnHeader();			this.ColumnHeader1 = new System.Windows.Forms.ColumnHeader();			this.btnCloseAll = new System.Windows.Forms.Button();			this.btnLaunch1 = new System.Windows.Forms.Button();			this.ListView1 = new System.Windows.Forms.ListView();			this.SuspendLayout();			// 			// btnClose1			// 			this.btnClose1.Location = new System.Drawing.Point(160, 176);			this.btnClose1.Name = "btnClose1";			this.btnClose1.Size = new System.Drawing.Size(112, 32);			this.btnClose1.TabIndex = 4;			this.btnClose1.Text = "Close Selected Process";			this.btnClose1.Click += new System.EventHandler(this.btnClose1_Click);			// 			// ColumnHeader2			// 			this.ColumnHeader2.Text = "Process ID";			this.ColumnHeader2.Width = 85;			// 			// ColumnHeader1			// 			this.ColumnHeader1.Text = "Window Title";			this.ColumnHeader1.Width = 160;			// 			// btnCloseAll			// 			this.btnCloseAll.Location = new System.Drawing.Point(160, 216);			this.btnCloseAll.Name = "btnCloseAll";			this.btnCloseAll.Size = new System.Drawing.Size(112, 32);			this.btnCloseAll.TabIndex = 3;			this.btnCloseAll.Text = "Close All Processes";			this.btnCloseAll.Click += new System.EventHandler(this.btnCloseAll_Click);			// 			// btnLaunch1			// 			this.btnLaunch1.Location = new System.Drawing.Point(32, 176);			this.btnLaunch1.Name = "btnLaunch1";			this.btnLaunch1.Size = new System.Drawing.Size(112, 72);			this.btnLaunch1.TabIndex = 1;			this.btnLaunch1.Text = "Start Notepad";			this.btnLaunch1.Click += new System.EventHandler(this.btnLaunch1_Click);			// 			// ListView1			// 			this.ListView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {																																								this.ColumnHeader1,																																								this.ColumnHeader2});			this.ListView1.Location = new System.Drawing.Point(22, 8);			this.ListView1.MultiSelect = false;			this.ListView1.Name = "ListView1";			this.ListView1.Size = new System.Drawing.Size(250, 152);			this.ListView1.TabIndex = 7;			this.ListView1.View = System.Windows.Forms.View.Details;			// 			// Form1			// 			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);			this.ClientSize = new System.Drawing.Size(292, 266);			this.Controls.AddRange(new System.Windows.Forms.Control[] {																																	this.btnCloseAll,																																	this.btnLaunch1,																																	this.ListView1,																																	this.btnClose1});			this.Name = "Form1";			this.Text = "Process Example";			this.Closing += new System.ComponentModel.CancelEventHandler(this.closing);			this.Load += new System.EventHandler(this.Form1_Load);			this.ResumeLayout(false);		}    #endregion  		[STAThread]		static void Main() 		{			Application.Run(new Form1());		}  		private void buildList()		{			ListViewItem itemAdd ; 			ListView1.Items.Clear();			processes = Process.GetProcessesByName(procName);			foreach (Process proc in processes)			{				itemAdd = ListView1.Items.Add(proc.MainWindowTitle);				itemAdd.SubItems.Add(proc.Id.ToString());			}		}		private void btnLaunch1_Click(object sender, System.EventArgs e)		{			ProcessStartInfo p = new ProcessStartInfo();			p.FileName = specialFolder + @"\eula.txt";			p.WindowStyle = ProcessWindowStyle.Minimized ;			Process proc =Process.Start(p);			proc.WaitForInputIdle();			buildList();		}		private void Form1_Load(object sender, System.EventArgs e)		{      		}		private void btnClose1_Click(object sender, System.EventArgs e)		{			try			{         				int procID=System.Convert.ToInt32(ListView1.SelectedItems[0].SubItems[1].Text);				Process tempProc=Process.GetProcessById(procID);				tempProc.CloseMainWindow();				tempProc.WaitForExit();				buildList();			}			catch			{				MessageBox.Show("Please select a process in the ListView before clicking this button." +					" Or the Process may have been closed by somebody." );				buildList();			}		}		private void btnCloseAll_Click(object sender, System.EventArgs e)		{			try			{				foreach (Process proc in processes)				{					proc.CloseMainWindow();					proc.WaitForExit();				}				buildList();			}			catch (System.NullReferenceException)			{				MessageBox.Show("No instances of Notepad running.");			}		}		private void closing(object sender, System.ComponentModel.CancelEventArgs e)		{			//Make sure that you do not leave any instances running.			if (processes != null && processes.Length!=0)				this.btnCloseAll_Click(this,e);		}	}} 						
    Note The code should be changed in Visual Studio 2005. For more information, visit the following MSDN Web site:
    By default, when you create a Windows Forms project, Visual C# adds one form to the project named Form1. The two files that represent the form are called Form1.cs and Form1.designer.cs. You write your code in Form1.cs. The Form1.designer.cs file is where the Windows Forms Designer writes the code that implements all the actions that you perform by dragging controls from the Toolbox.

    Note It is recommended that you collapse the area named Windows Form Designer generated code.
  4. Run the application.
  5. Click Start Notepad one or more times.
  6. Click an instance of Notepad in the ListView control window and select Close Process. This closes the specific instance of Notepad that you selected. You can also select Close All Processes to close all of the running instances of Notepad.


This sample uses the Id property of the Process class to differentiate between instances of the application. The Id property is a good candidate for this task because all process IDs are unique. The same is true of the WindowHandle property, so you can also use the WindowHandle property of a Process object to differentiate between instances of the application.

Other properties can also be used, although they are less well-suited to the task. For example, if you do not know the process ID of a specific process or have the handle of the main window, you can use the MainWindowTitle property to help identify the proper instance. The MainWindowTitle property may not be unique, but it can help you to isolate the desired application.

The sample in this article uses a Windows application and employs the CloseMainWindow method to close the application. CloseMainWindow does not work with a non-Windows application. If the application that you are attempting to close does not have a window (for example, a console application), you must use the Kill method to close the application.

back to the top


For more information, see the following Microsoft Developer Network (MSDN) Web site: back to the top

Article ID: 305603 - Last Review: 12/11/2006 21:01:33 - Revision: 2.4

  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# 2005
  • kbdiagnostics kbhowtomaster kbsample KB305603