The Process Class When an application is executed, it creates a process. Each process consumes memory and other system resources and is uniquely identified by a process identifier (PID). The System.Diagnostics namespace includes a Process class. The methods of the Process class may be used to start and stop running processes, and its properties can be used to obtain information about running processes. Starting and Stopping Processes The Start method of the Process class may be used to start an instance of the target process, using startup information specified in the StartInfo property to allow runtime configuration of the application's environment. The Process class also includes two methods that can be used to terminate a running process: CloseMainWindow and Kill . | The Process class can only be used to start and stop processes on the local system, although it is possible to access process information on both local and remote systems using this class. | CloseMainWindow is equivalent to clicking the close icon of an application, and it can only be used with applications that have a user interface and participate in the Windows message loop. The Kill method must be used for applications lacking a user interface or those that do not participate in the Windows message loop, such as MS-DOS-based executables. The Kill method will terminate an application immediately without saving data or performing resource cleanup. Table 14.1 details several members of the Process class that are useful for starting or stopping processes. Table 14.1. Members of the Process Class Useful for Starting or Stopping Processes Member | Type | Description | CloseMainWindow | Method | Closes a process with a user interface by sending a close message to its main window. | EnableRaisingEvents | Property | Specifies if an Exited event is raised when the process terminates. | ExitCode | Property | The exit value specified by a process upon termination. | Exited | Event | Fires upon process termination. | ExitTime | Property | The time when the process ended. | GetProcessById | Method | A Process object representing a running process with the specified PID. | GetProcesses | Method | Returns an array of Process objects, where each element represents a running process. | GetProcessesByName | Method | Returns an array of Process objects, where each element represents a running process with the specified name . | HasExited | Property | Indicates whether a process has been terminated . | Id | Property | The PID of a process. | Kill | Method | Immediately terminates a running process. | Start | Method | Launches a new process. | StartInfo | Property | Specifies the properties to pass to the Start method. | WaitForExit | Method | A period to wait for process termination, blocking the current thread of execution until the time has expired or the process has terminated. | WaitForInputIdle | Method | Causes a Process object to wait for the system to enter an idle state. | You can create a sample form that can start and stop instances of the Calculator application by performing the following steps: -
Open an instance of Visual Studio .NET and create a new Visual Basic .NET Windows Application project. -
Place two GroupBox controls, three Button controls ( btnLaunchCalculator , btnCloseRecentCalculator , and btnCloseAllCalculators ), and two Label controls (one named lblLiveCalculators ) on the default form in the project. Set the Text property of lblLiveCalculators to 0. Figure 14.1 shows a design for this form. Figure 14.1. A form to demonstrate the Process class. -
Switch to the form's code view and add the following statement at the top of the form's module: Imports System.Diagnostics -
Add the following code to your form: Dim arrCalculators As ArrayList = New ArrayList() Private Sub Calculator_Exited(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim p As Process = CType(sender, Process) arrCalculators.RemoveAt(arrCalculators.IndexOf(p.Id)) lblLiveCalculators.Text = _ (Int32.Parse(lblLiveCalculators.Text) - 1).ToString() End Sub Private Sub btnLaunchCalculator_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnLaunchCalculator.Click Dim prcCalculator As Process = New Process() prcCalculator.StartInfo.FileName = "calc.exe " prcCalculator.EnableRaisingEvents = True AddHandler prcCalculator.Exited, _ AddressOf Calculator_Exited prcCalculator.Start() prcCalculator.WaitForInputIdle() arrCalculators.Add(prcCalculator.Id) lblLiveCalculators.Text = _ (Int32.Parse(lblLiveCalculators.Text) + 1).ToString() End Sub Private Sub btnCloseRecentCalculator_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnCloseRecentCalculator.Click If arrCalculators.Count > 0 Then Dim intId As Integer = _ CInt(arrCalculators(arrCalculators.Count - 1)) Try Dim p As Process = Process.GetProcessById(intId) p.CloseMainWindow() Catch ex As Exception Trace.WriteLine(ex.Message) End Try End If End Sub Private Sub btnCloseAllCalculators_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnCloseAllCalculators.Click Dim arrCalculators() As Process = _ Process.GetProcessesByName("calc") Dim prcCalculator As Process For Each prcCalculator In arrCalculators prcCalculator.CloseMainWindow() Next End Sub -
Set the form as the startup object and run your project. When you click the Launch button, a new instance of the Calculator process is launched. Clicking the Close Most Recent button will terminate the most recent instance of the Calculator process started by this application. The Close All Calculators button will stop all running instances of the Calculator process. | This example showed you how to use the Process class directly from code. If you prefer, you may also use the Process control from the Toolbox window, configuring its StartInfo property to include the filename of the target process and its startup parameters, to launch programs. | Getting Process Information Process information may be programmatically accessed using the properties of an instance of the Process class created for a process running on a local or remote system. Table 14.2 details some of the useful properties exposed by this class. Table 14.2. Useful Properties of the Process Class Property | Description | MachineName | The name of the machine where the process is running | MainModule | The main module of the process | MainWindowTitle | The caption in the main window of the process | Modules | Modules loaded by the associated process | PriorityClass | The priority class for the process | ProcessName | The name of the process | ProcessorAffinity | Specifies the processors on which the threads in this process can be scheduled to run | Responding | Indicates whether the user interface is responding | StandardError | Provides access to a StreamReader object, allowing you to read error output | StandardInput | Provides access to a StreamWriter object, allowing you to write input to the process | StandardOutput | Provides access to a StreamReader object, allowing you to read output from the process | StartTime | The process start time | Threads | Threads running in the associated process | TotalProcessorTime | The total processor time used by the process | UserProcessorTime | The total user processor time used by the process | VirtualMemorySize | The size of virtual memory used by the process | WorkingSet | The physical memory used by the process | |