Microsoft KB Archive/305603

= How to use Visual C# to close another application =

Article ID: 305603

Article Last Modified on 12/11/2006

-

APPLIES TO


 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C# 2005

-



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

IN THIS TASK
SUMMARY
 * Discussion of the Programming Logic
 * Steps to Build the Sample

REFERENCES



SUMMARY
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

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 = &quot;Notepad&quot;;

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(&quot;Please select a process in the ListView before clicking this button.&quot; +        &quot; Or the Process may have been closed by somebody.&quot; ); 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(&quot;No instances of Notepad running.&quot;); } back to the top

Steps to Build the Sample
 Start a new Visual C# Windows application in Visual Studio .NET. Right-click the default form, Form1.cs, and select View Code.  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 description for Form1. ///    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; ///        /// Required designer variable. ///        private System.ComponentModel.Container components = null;

private Process[] processes; private string procName = &quot;Notepad&quot;; 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. //        }

///        /// Clean up any resources that are being used. ///        protected override void Dispose( bool disposing ) {           if( disposing ) {               if (components != null) {                   components.Dispose; }           }            base.Dispose( disposing ); }

#region Windows Form Designer generated code ///        /// Required method for Designer support - do not modify /// the contents of this method with the code editor. ///        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 = &quot;btnClose1&quot;; this.btnClose1.Size = new System.Drawing.Size(112, 32); this.btnClose1.TabIndex = 4; this.btnClose1.Text = &quot;Close Selected Process&quot;; this.btnClose1.Click += new System.EventHandler(this.btnClose1_Click); //            // ColumnHeader2 //            this.ColumnHeader2.Text = &quot;Process ID&quot;; this.ColumnHeader2.Width = 85; //            // ColumnHeader1 //            this.ColumnHeader1.Text = &quot;Window Title&quot;; this.ColumnHeader1.Width = 160; //            // btnCloseAll //            this.btnCloseAll.Location = new System.Drawing.Point(160, 216); this.btnCloseAll.Name = &quot;btnCloseAll&quot;; this.btnCloseAll.Size = new System.Drawing.Size(112, 32); this.btnCloseAll.TabIndex = 3; this.btnCloseAll.Text = &quot;Close All Processes&quot;; this.btnCloseAll.Click += new System.EventHandler(this.btnCloseAll_Click); //            // btnLaunch1 //            this.btnLaunch1.Location = new System.Drawing.Point(32, 176); this.btnLaunch1.Name = &quot;btnLaunch1&quot;; this.btnLaunch1.Size = new System.Drawing.Size(112, 72); this.btnLaunch1.TabIndex = 1; this.btnLaunch1.Text = &quot;Start Notepad&quot;; 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 = &quot;ListView1&quot;; 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 = &quot;Form1&quot;; this.Text = &quot;Process Example&quot;; 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 + @&quot;\eula.txt&quot;; 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(&quot;Please select a process in the ListView before clicking this button.&quot; +                    &quot; Or the Process may have been closed by somebody.&quot; ); 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(&quot;No instances of Notepad running.&quot;); }       }

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.  Run the application. Click Start Notepad one or more times. 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.</li></ol>