public class Process : Component
|
The Process component is a useful tool for starting, stopping, controlling, and monitoring applications. Using the Process component, you can obtain a list of the processes that are running or start a new process. A Process component is used to access system processes. After a Process component has been initialized, it can be used to obtain information about the running process. Such information includes the set of threads, the loaded modules (.dll and .exe files), and performance information such as the amount of memory the process is using.
The process component obtains information about a group of properties all at once. After the Process component has obtained information about one member of any group, it will cache the values for the other properties in that group and not obtain new information about the other members of the group until you call the Process.Refresh method. Therefore, a property value is not guaranteed to be any newer than the last call to the Process.Refresh method. The group breakdowns are operating-system dependent.
A system process is uniquely identified on the system by its process identifier. Like many Windows resources, a process is also identified by its handle, which might not be unique on the computer. A handle is the generic term for an identifier of a resource. The operating system persists the process handle, which is accessed through the Process.Handle property of the Process component, even when the process has exited. Thus, you can get the process's administrative information, such as the Process.ExitCode (usually either zero for success or a nonzero error code) and the Process.ExitTime. Handles are an extremely valuable resource, so leaking handles is more virulent than leaking memory.
ctor #1 | Default constructor. This constructor is called by derived class constructors to initialize state in this type. Initializes a new instance of the Process class. |
Container (inherited from System.ComponentModel.Component) |
Read-only See base class member description: System.ComponentModel.Component.Container Gets the IContainer that contains the Component. |
EnableRaisingEvents | Read-write Gets or sets whether the Process.Exited event should be raised when the process terminates. |
ExitCode | Read-only Gets the value that the associated process specified when it terminated. |
ExitTime | Read-only Gets the time that the associated process exited. |
Handle | Read-only Returns the associated process's native handle. |
HasExited | Read-only Gets a value indicating whether the associated process has been terminated. |
Id | Read-only Gets the unique identifier for the associated process. |
Site (inherited from System.ComponentModel.Component) |
Read-write See base class member description: System.ComponentModel.Component.Site Gets or sets the ISite of the Component. |
StandardError | Read-only Gets a StreamReader through which to read error output from the application. |
StandardInput | Read-only Gets a StreamWriter through which the application can write input to the process. |
StandardOutput | Read-only Gets a StreamReader through which the application can read output from the process. |
StartInfo | Read-write Gets or sets the properties to pass to the Process.Start method of the Process. |
SynchronizingObject | Read-write Gets or sets the object used to marshal the event handler calls that are issued as a result of a process exit event. |
Close | Frees all the resources that are associated with this component. |
CreateObjRef (inherited from System.MarshalByRefObject) |
See base class member description: System.MarshalByRefObject.CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. |
Dispose (inherited from System.ComponentModel.Component) |
Overloaded:Dispose() See base class member description: System.ComponentModel.Component.DisposeReleases all resources used by the Component. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetCurrentProcess | Gets a new Process component and associates it with the currently active process. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetLifetimeService (inherited from System.MarshalByRefObject) |
See base class member description: System.MarshalByRefObject.GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
InitializeLifetimeService (inherited from System.MarshalByRefObject) |
See base class member description: System.MarshalByRefObject.InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. |
Kill | Immediately stops the associated process. |
Refresh | Discards any information about the associated process that has been cached inside the process component. |
Start | Overloaded:Start() Starts (or reuses) the process resource that is specified by the Process.StartInfo property of this Process component and associates it with the component. |
Start | Overloaded:Start(ProcessStartInfo startInfo) Starts the process resource that is specified by the parameter containing process start information (for example, the file name of the process to start) and associates the resource with a new Process component. |
Start | Overloaded:Start(string fileName) Starts a process resource by specifying the name of a document or application file and associates the resource with a new Process component. |
Start | Overloaded:Start(string fileName, string arguments) Starts a process resource by specifying the name of an application and a set of command line arguments, and associates the resource with a new Process component. |
ToString (inherited from System.Object) |
See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
WaitForExit | Overloaded:WaitForExit() Instructs the Process component to wait indefinitely for the associated process to exit. |
WaitForExit | Overloaded:WaitForExit(int milliseconds) Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. |
Disposed (inherited from System.ComponentModel.Component) |
See base class member description: System.ComponentModel.Component.Disposed Adds an event handler to listen to the Component.Disposed event on the component. |
Exited | Occurs when a process exits. |
DesignMode (inherited from System.ComponentModel.Component) |
Read-only See base class member description: System.ComponentModel.Component.DesignMode Gets a value that indicates whether the Component is currently in design mode. |
Events (inherited from System.ComponentModel.Component) |
Read-only See base class member description: System.ComponentModel.Component.Events Gets the list of event handlers that are attached to this Component. |
Dispose | Overloaded:Dispose(bool disposing) Overridden: Supports the Shared Source CLI infrastructure and is not intended to be used directly from your code |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
GetService (inherited from System.ComponentModel.Component) |
See base class member description: System.ComponentModel.Component.GetService Returns an object that represents a service provided by the Component or by its Container. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
OnExited | Raises the Process.Exited event. |
Hierarchy:
public Process(); |
You have two options for associating a new Process component with a process on the computer. The first option is to use the constructor to create the Process component, set the appropriate members of the Process.StartInfo property and call Process.Start to associate the Process with a new system process. The second option is to associate the Process with a running system process by using System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) or one of the System.Diagnostics.Process.GetProcesses (not supported on the shared source CLI) return values.
If you use a static overload of the Process.Start method to start a new system process, the method creates a new Process component and associates it with the process.
When the ProcessStartInfo.UseShellExecute property is set to its default value, true, you can start applications and documents in a way that is similar to using the Run dialog box of the Windows Start menu. When ProcessStartInfo.UseShellExecute is false, you can start only executables.
Any executable file that you can call from the command line can be started in one of two ways: by setting the appropriate members of the Process.StartInfo property and calling the Process.Start method with no parameters, or by passing the appropriate parameter to the static Process.Start member.
You can create a Process component by using the constructor, one of the static Process.Start overloads, or any of the System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) , System.Diagnostics.Process.GetProcesses (not supported on the shared source CLI) , or System.Diagnostics.Process.GetProcessesByName (not supported on the shared source CLI) methods. After you have done so, you have a view into the associated process. This is not a dynamic view that updates itself automatically when the process properties have changed in memory. Instead, you must call Process.Refresh for the component to update the Process property information in your application.
public IContainer Container {get;}
|
protected bool DesignMode {get;}
|
public bool EnableRaisingEvents {get; set;}
|
When an associated process exits after being shut down by the operation system either through a normal or abnormal termination, the operating system notifies each process component to which the process was associated, as long as the component's Process.EnableRaisingEvents value is true. If a component started the process, the component can then access the administrative information for the associated process, which is still being stored by the operating system. Such information includes the Process.ExitTime, and the Process.ExitCode.
After the associated process exits, the Process.Handle of the component no longer points to an existing process resource. Instead, it can be used only to access the operating system's information about the process resource. The operating system is aware that there are handles to exited processes that have not been released by Process components, so it keeps the Process.ExitTime and Process.Handle information in memory.
There is a cost associated with watching for a process to exit. If Process.EnableRaisingEvents is true, the Process.Exited event is raised when the associated process terminates. The procedures that you have specified for the Process.Exited event run at that time.
Sometimes, your application starts a process but does not need to be notified of its closure. For example, your application can start Notepad to allow the user to perform text editing, but make no further use of the Notepad application. You can choose to not be notified when the process exits, because it is not relevant to the continued operation of your application. Setting Process.EnableRaisingEvents to false saves system resources.
protected EventHandlerList Events {get;}
|
public int ExitCode {get;}
|
Exception Type | Condition |
---|---|
InvalidOperationException | The process has not exited. -or- The process Process.Handle is not valid. |
main()
procedure. How you choose to implement it is specific to your application.Developers usually indicate a successful exit by an Process.ExitCode value of zero, and designate errors by nonzero values that the calling method can use to identify the cause of an abnormal process termination. It is not necessary to follow these guidelines, but they are the convention.
If you try to get the Process.ExitCode before the process has exited, the attempt throws an exception. Examine the Process.HasExited property first to verify whether the associated process has terminated.
You can use the System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or the Process.Kill method to cause an associated process to exit.
There are two ways of being notified when the associated process exits: synchronously and asynchronously. Synchronous notification relies on calling the Process.WaitForExit method to pause the processing of your application until the associated component exits. Asynchronous notification relies on the Process.Exited event. In either case, Process.EnableRaisingEvents must be set to true for the Process component to receive notification that the process has exited.
public DateTime ExitTime {get;}
|
Exception Type | Condition |
---|---|
PlatformNotSupportedException | You are accessing this member using Windows 98. |
public IntPtr Handle {get;}
|
Exception Type | Condition |
---|---|
InvalidOperationException | The process has not been started. The Process.Handle property cannot be read because there is no process associated with this Process instance. -or- The Process instance has been attached to a running process but you do not have the necessary permissions to get a handle with full access rights. |
Only processes started through a call to Process.Start set the Process.Handle property of the corresponding Process instances.
public bool HasExited {get;}
|
Exception Type | Condition |
---|---|
InvalidOperationException | There is no process associated with the object. |
Win32Exception | The exit code for the process could not be retrieved. |
A process can terminate independently of your code. If you started the process using this component, the system updates the value of Process.HasExited automatically, even if the associated process exits independently.
public int Id {get;}
|
Exception Type | Condition |
---|---|
InvalidOperationException | The process's Process.Id property has not been set. -or- There is no process associated with this Process object. |
You can connect a process that is running on a local or remote computer to a new Process instance by passing the process identifier to the System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) method. System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) is a static method that creates a new component and sets the Process.Id property for the new Process instance automatically.
Process identifiers can be reused by the system. The Process.Id property value is unique only while the associated process is running. After the process has terminated, the system can reuse the Process.Id property value for an unrelated process.
Because the identifier is unique on the system, you can pass it to other threads as an alternative to passing a Process instance. This action can save system resources yet guarantee that the process is correctly identified.
public virtual ISite Site {get; set;}
|
The property value is null if the Component is removed from its IContainer. Assigning null to this property does not necessarily remove the Component from the IContainer.
A Component might or might not have a name. If a Component is given a name, the name must be unique among other Component objects within its IContainer. The ISite stores the name of the Component; therefore, you can only name a Component if it has an ISite associated with it.
public StreamReader StandardError {get;}
|
Exception Type | Condition |
---|---|
InvalidOperationException | The Process.StandardError value has not been defined. The Process.StartInfo property's ProcessStartInfo.RedirectStandardError may be false. |
The Process component communicates with a child process via a pipe. If a child process writes enough data to the pipe to fill the buffer, the child will block until the parent reads the data from the pipe. This can cause deadlock if your application is reading all output to standard error and standard output, for example, using the following C# code.
Process p = new Process("...", "..."); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); string output = p.StandardOutput.ReadToEnd();
In this instance, both the parent and the child processes would be blocked, as the filled pipe prevents the child process from completing, while the parent process is waiting indefinitely for the child process to exit.
This problem can be solved by moving the
ReadToEnd()
before the
WaitForExit()
, as follows.
Process p = new Process("...", "..."); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit();
A similar problem arises if you redirect both standard output and standard error and then try to read both, for example using the following C# code.
string output = p.StandardOutput.ReadToEnd(); string error = p.StandardError.ReadToEnd(); p.WaitForExit();
In this case, if the child process writes any text to standard error it will block the process, because the parent process cannot read from standard error until it has finished reading from standard output. However, the parent process will not read from standard output until the process ends. A recommended solution to this situation is to create two threads so that your application can read the output of each stream on a separate thread.
public StreamWriter StandardInput {get;}
|
Exception Type | Condition |
---|---|
InvalidOperationException | The Process.StandardInput value has not been defined. The Process.StartInfo property's ProcessStartInfo.RedirectStandardInput may be false or you may not have defined a valid StreamWriter to read from. |
public StreamReader StandardOutput {get;}
|
Exception Type | Condition |
---|---|
InvalidOperationException | The Process.StandardOutput value has not been defined. The Process.StartInfo property's ProcessStartInfo.RedirectStandardOutput may be false or you may not have defined a valid StreamReader to write to. |
The Process component communicates with a child process via a pipe. If a child process writes enough data to the pipe to fill the buffer, the child will block until the parent reads the data from the pipe. This can cause deadlock if your application is reading all output to standard error and standard output, for example, using the following C# code.
Process p = new Process("...", "..."); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); string output = p.StandardOutput.ReadToEnd();
In this instance, both the parent and the child processes would be blocked, as the filled pipe prevents the child process from completing, while the parent process is waiting indefinitely for the child process to exit.
This problem can be solved by moving the
ReadToEnd()
before the
WaitForExit()
, as follows.
Process p = new Process("...", "..."); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit();
A similar problem arises if you redirect both standard output and standard error and then try to read both, for example using the following C# code.
string output = p.StandardOutput.ReadToEnd(); string error = p.StandardError.ReadToEnd(); p.WaitForExit();
In this case, if the child process writes any text to standard error it will block the process, because the parent process cannot read from standard error until it has finished reading from standard output. However, the parent process will not read from standard output until the process ends. A recommended solution to this situation is to create two threads so that your application can read the output of each stream on a separate thread.
public ProcessStartInfo StartInfo {get; set;}
|
Exception Type | Condition |
---|---|
ArgumentException | The value that specifies the Process.StartInfo is null. |
The only necessary Process.StartInfo member to set is the ProcessStartInfo.FileName property. Starting a process by specifying the ProcessStartInfo.FileName property is similar to typing the information in the Run dialog box of the Windows Start menu. Therefore, the ProcessStartInfo.FileName property does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application installed on the system. For example the ProcessStartInfo.FileName can have a .txt extension if you have associated text files with an editor, such as Notepad, or it can have a .doc if you have associated .doc files with a word processing tool, such as Microsoft Word. Similarly, in the same way that the Run dialog box can accept an executable file name with or without the .exe extension, the .exe extension is optional in the ProcessStartInfo.FileName member. For example, you can set the ProcessStartInfo.FileName property to either "Notepad.exe" or "Notepad".
If the file name involves a non-executable file, such as a .doc file, you can include a verb specifying what action to take on the file. For example, you could set the System.Diagnostics.ProcessStartInfo.Verb (not supported on the shared source CLI) to "Print" for a file ending in the .doc extension. The file name specified in the ProcessStartInfo.FileName property does not need to have an extension if you manually enter a value for the System.Diagnostics.ProcessStartInfo.Verb (not supported on the shared source CLI) property. However, if you use the System.Diagnostics.ProcessStartInfo.Verbs (not supported on the shared source CLI) property to determine what verbs are available, you must include the file extension.
When the process is started, the file name is the file that populates the (read-only) System.Diagnostics.Process.MainModule (not supported on the shared source CLI) property. If you want to retrieve the executable file that is associated with the process after the process has started, use the System.Diagnostics.Process.MainModule (not supported on the shared source CLI) property. If you want to set the executable file of a Process instance for which an associated process has not been started, use the Process.StartInfo property's ProcessStartInfo.FileName member. Because the members of the Process.StartInfo property are arguments that are passed to the Process.Start method of a process, changing the ProcessStartInfo.FileName property after the associated process has started will not reset the System.Diagnostics.Process.MainModule (not supported on the shared source CLI) property. These properties are used only to initialize the associated process.
public ISynchronizeInvoke SynchronizingObject {get; set;}
|
When the Process.Exited event is handled by a visual Windows Forms component, such as a Button, accessing the component through the system thread pool might not work, or may result in an exception. Avoid this by setting Process.SynchronizingObject to a Windows Forms component, which causes the methods handling the Process.Exited event to be called on the same thread on which the component was created.
If the Process is used inside Visual Studio .NET in a Windows Forms designer, Process.SynchronizingObject is automatically set to the control containing the Process. For example, if you place a Process on a designer for Form1 (which inherits from Form) the Process.SynchronizingObject property of Process is set to the instance of Form1.
Typically, this property is set when the component is placed inside a control or form, because those components are bound to a specific thread.
private MyButton button1; private void button1_Click(object sender, System.EventArgs e) { Process myProcess = new Process(); ProcessStartInfo myProcessStartInfo= new ProcessStartInfo("mspaint"); myProcess.StartInfo = myProcessStartInfo; myProcess.Start(); myProcess.Exited += new EventHandler(button1.MyProcessExited); // Set 'EnableRaisingEvents' to true, to raise 'Exited' event when process is terminated. myProcess.EnableRaisingEvents = true; // Set method handling the exited event to be called ; // on the same thread on which MyButton was created. myProcess.SynchronizingObject = button1; MessageBox.Show("Waiting for the process 'mspaint' to exit...."); myProcess.WaitForExit(); myProcess.Close(); } } public class MyButton:Button { public void MyProcessExited(Object source, EventArgs e) { MessageBox.Show("The process has exited."); } }
public void Close(); |
requestedType
Exception Type | Condition |
---|---|
RemotingException | This instance is not a valid remoting object. |
public void Dispose(); |
protected override void Dispose( |
disposing
~Process(); |
public static Process GetCurrentProcess(); |
Like the similar System.Diagnostics.Process.GetProcessById (not supported on the shared source CLI) , System.Diagnostics.Process.GetProcessesByName (not supported on the shared source CLI) , and System.Diagnostics.Process.GetProcesses (not supported on the shared source CLI) methods, Process.GetCurrentProcess associates an existing resource with a new Process component.
public virtual int GetHashCode(); |
public object GetLifetimeService(); |
service
This value is null if the Component does not provide the specified service.
public Type GetType(); |
public virtual object InitializeLifetimeService(); |
public class MyClass : MarshalByRefObject { public override Object InitializeLifetimeService() { ILease lease = (ILease)base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.FromMinutes(1); lease.SponsorshipTimeout = TimeSpan.FromMinutes(2); lease.RenewOnCallTime = TimeSpan.FromSeconds(2); } return lease; } }
public void Kill(); |
Exception Type | Condition |
---|---|
Win32Exception | The associated process could not be terminated. |
SystemException | No process Process.Id has been set, and a Process.Handle from which the Process.Id property can be determined does not exist. -or- There is no process associated with this Process object. -or- You are attempting to call Process.Kill for a process that is running on a remote computer. The method is available only for processes running on the local computer. |
InvalidOperationException | The process has already exited. |
Data edited by the process or resources allocated to the process can be lost if you call Process.Kill. Process.Kill causes an abnormal process termination and should be used only when necessary. System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) enables an orderly termination of the process and closes all windows, so it is preferable for applications with an interface. If System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) fails, you can use Process.Kill to terminate the process. Process.Kill is the only way to terminate processes that do not have graphical interfaces.
You can call Process.Kill and System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) only for processes that are running on the local computer. You cannot cause processes on remote computers to exit. You can only view information for processes running on remote computers.
protected object MemberwiseClone(); |
protected void OnExited(); |
As an alternative to Process.OnExited, you can write your own event handler. You create your own event handler delegate and your own event-handling method.
Raising an event invokes the event handler through a delegate. For an overview, see the conceptual topic at MSDN: providingeventfunctionality.
public void Refresh(); |
When a Process component is associated with a process resource, the property values of the Process are immediately populated according to the status of the associated process. If the information about the associated process subsequently changes, those changes are not reflected in the Process component's cached values. The Process component is a snapshot of the process resource at the time they are associated. To view the current values for the associated process, call the Process.Refresh method.
public bool Start(); |
Exception Type | Condition |
---|---|
InvalidOperationException | No file name was specified in the Process component's Process.StartInfo. -or- The ProcessStartInfo.UseShellExecute member of the Process.StartInfo property is true while ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput, or ProcessStartInfo.RedirectStandardError is true. |
Win32Exception | There was an error in opening the associated file. |
ObjectDisposedException | The process object has already been disposed. |
This overload of Process.Start is not a static method. You must call it for an instance of the Process class. Before calling Process.Start, you must first specify Process.StartInfo property information for this Process instance, because that information is used to determine the process resource to start.
The other overloads of the Process.Start method are static members. You do not need to create an instance of the Process component before you call those overloads of the method. Instead, you can call Process.Start for the Process class itself, and a new Process component is created if the process was started. Or, null is returned if a process was reused. The process resource is automatically associated with the new Process component that is returned by the Process.Start method.
The Process.StartInfo members can be used to duplicate the functionality of the Run dialog box of the Windows Start menu. Anything that can be typed into a command line can be started by setting the appropriate values in the Process.StartInfo property. The only Process.StartInfo property that must be set is the ProcessStartInfo.FileName property. The ProcessStartInfo.FileName property does not have to be an executable file. It can be of any file type for which the extension has been associated with an application that is installed on the system. For example, the ProcessStartInfo.FileName property can have a .txt extension if you have associated text files with an editor, such as Notepad, or it can have a .doc extension if you have associated .doc files with a word processing tool, such as Microsoft Word.
In the command line, you can specify actions to take for certain types of files. For example, you can print documents or edit text files. Specify these actions using the System.Diagnostics.ProcessStartInfo.Verb (not supported on the shared source CLI) member of the Process.StartInfo property. For other types of files, you can specify command line arguments when you start the file from the Run dialog box. For example, you can pass a URL as an argument if you specify your browser as the ProcessStartInfo.FileName. These arguments can be specified in the Process.StartInfo property's ProcessStartInfo.Arguments member.
Whenever you use Process.Start to start a process, you might need to close it or you risk losing system resources. Close processes using System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill.
A note about apartment states in managed threads is necessary here. When ProcessStartInfo.UseShellExecute is true on the process component's Process.StartInfo property, make sure you have set a threading model on your application by setting the attribute
[STAThread]
on the
main()
method. Otherwise, a managed thread can be in an unknown state or put in the MTA state, the latter of which conflicts with ProcessStartInfo.UseShellExecute being true. Some methods require that the apartment state not be unknown. If the state is not explicitly set, when the application encounters such a method, it defaults to MTA, and once set, the apartment state cannot be changed. However, MTA causes an exception to be thrown when the operating system shell is managing the thread.
StartProcess takes two parameters. The first parameter is the name of a document, meaning any file that has an open action associated with it (for example, MyDoc.doc or MyFile.txt). The second parameter is the document's extension (.doc, .txt, .htm., or .xls). Using the extension, the StartProcess procedure associates an application with the Process component's Process.StartInfo property. Then, the document itself is passed as an argument with which the application is opened. In the case of Excel or Word, the document is opened in order to be printed. In the case of Notepad or Internet Explorer, the document is only loaded into the application's window.
The file name and arguments are the same as you would type into the Run dialog box of the Windows Start menu.
public static Process Start(Process Start( |
startInfo
Exception Type | Condition |
---|---|
InvalidOperationException | No file name was specified in the startInfo parameter's ProcessStartInfo.FileName property. -or- The ProcessStartInfo.UseShellExecute member of the startInfo parameter is true while ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput, or ProcessStartInfo.RedirectStandardError is true. |
ArgumentException | The startInfo parameter is null. |
Win32Exception | There was an error in opening the associated file. |
ObjectDisposedException | The process object has already been disposed. |
This overload lets you start a process without first creating a new Process instance. Using this overload with a ProcessStartInfo parameter is an alternative to the explicit steps of creating a new Process instance, setting its Process.StartInfo properties, and calling Process.Start for the Process instance.
Using a ProcessStartInfo instance as the parameter lets you call Process.Start with the most control over what is passed into the call to start the process. If you need to pass only a file name or a file name and arguments, it is not necessary to create a new ProcessStartInfo instance, although that is an option. The only Process.StartInfo property that must be set is the ProcessStartInfo.FileName property. The ProcessStartInfo.FileName property does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application that is installed on the system. For example, the ProcessStartInfo.FileName property can have a .txt extension if you have associated text files with an editor, such as Notepad, or it can have a .doc extension if you have associated .doc files with a word processing tool, such as Microsoft Word.
Unlike the other overloads, the overload of Process.Start that has no parameters is not a static member. Use that overload when you have already created a Process instance, specified start information (including the file name), and want to start a process resource and associate it with the existing Process instance. Use one of the static overloads when you want to create a new Process component rather than start a process for an existing component. Both this overload and the overload that has no parameters allow you to specify the start information for the process resource by using a ProcessStartInfo instance.
Whenever you use Process.Start to start a process, you might need to close it or you risk losing system resources. Close processes using System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill.
A note about apartment states in managed threads is necessary here. When ProcessStartInfo.UseShellExecute is true on the startInfo parameter, make sure you have set a threading model on your application by setting the attribute
[STAThread]
on the
main()
method. Otherwise, a managed thread can be in an unknown state or put in the MTA state, the latter of which conflicts with ProcessStartInfo.UseShellExecute being true. Some methods require that the apartment state not be unknown. If the state is not explicitly set, when the application encounters such a method, it defaults to MTA, and once set, the apartment state cannot be changed. However, MTA causes an exception to be thrown when the operating system shell is managing the thread.
fileName
Exception Type | Condition |
---|---|
ArgumentException | The fileName parameter is null. |
Win32Exception | There was an error in opening the associated file. |
ObjectDisposedException | The process object has already been disposed. |
This overload lets you start a process without first creating a new Process instance. The overload is an alternative to the explicit steps of creating a new Process instance, setting the ProcessStartInfo.FileName member of the Process.StartInfo property, and calling Process.Start for the Process instance.
Starting a process by specifying its file name is similar to typing the information in the Run dialog box of the Windows Start menu. Therefore, the file name does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application installed on the system. For example the file name can have a .txt extenstion if you have associated text files with an editor, such as Notepad, or it can have a .doc if you have associated .doc files with a word processing tool, such as Microsoft Word. Similarly, in the same way that the Run dialog box can accept an executable file name with or without the .exe extension, the .exe extension is optional in the fileName parameter. For example, you can set the fileName parameter to either "Notepad.exe" or "Notepad".
Unlike the other overloads, the overload of Process.Start that has no parameters is not a static member. Use that overload when you have already created a Process instance, specified start information (including the file name), and want to start a process resource and associate it with the existing Process instance. Use one of the static overloads when you want to create a new Process component rather than start a process for an existing component. Both this overload and the overload that has no parameters allow you to specify the file name of the process resource to start.
Whenever you use Process.Start to start a process, you might need to close it or you risk losing system resources. Close processes using System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill.
A note about apartment states in managed threads is necessary here. When ProcessStartInfo.UseShellExecute is true on the process component's Process.StartInfo property, make sure you have set a threading model on your application by setting the attribute
[STAThread]
on the
main()
method. Otherwise, a managed thread can be in an unknown state or put in the MTA state, the latter of which conflicts with ProcessStartInfo.UseShellExecute being true. Some methods require that the apartment state not be unknown. If the state is not explicitly set, when the application encounters such a method, it defaults to MTA, and once set, the apartment state cannot be changed. However, MTA causes an exception to be thrown when the operating system shell is managing the thread.
fileName
arguments
Exception Type | Condition |
---|---|
ArgumentException | The fileName or arguments parameter is null. |
Win32Exception | There was an error in opening the associated file. |
ObjectDisposedException | The process object has already been disposed. |
This overload lets you start a process without first creating a new Process instance. The overload is an alternative to the explicit steps of creating a new Process instance, setting the ProcessStartInfo.FileName and ProcessStartInfo.Arguments members of the Process.StartInfo property, and calling Process.Start for the Process instance.
Starting a process by specifying its file name and arguments is similar to typing the file name and command line arguments in the Run dialog box of the Windows Start menu. Therefore, the file name does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application installed on the system. For example the file name can have a .txt extenstion if you have associated text files with an editor, such as Notepad, or it can have a .doc if you have associated .doc files with a word processing tool, such as Microsoft Word. Similarly, in the same way that the Run dialog box can accept an executable file name with or without the .exe extension, the .exe extension is optional in the fileName parameter. For example, you can set the fileName parameter to either "Notepad.exe" or "Notepad". If the fileName parameter represents an executable file, the arguments parameter may represent a file to act upon, such as the text file in
Notepad.exe
myfile.txt
.
Unlike the other overloads, the overload of Process.Start that has no parameters is not a static member. Use that overload when you have already created a Process instance, specified start information (including the file name), and want to start a process resource and associate it with the existing Process instance. Use one of the static overloads when you want to create a new Process component rather than start a process for an existing component. Both this overload and the overload that has no parameters allow you to specify the file name of the process resource to start and command line arguments to pass.
Whenever you use Process.Start to start a process, you might need to close it or you risk losing system resources. Close processes using System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) or Process.Kill.
A note about apartment states in managed threads is necessary here. When ProcessStartInfo.UseShellExecute is true on the process component's Process.StartInfo property, make sure you have set a threading model on your application by setting the attribute
[STAThread]
on the
main()
method. Otherwise, a managed thread can be in an unknown state or put in the MTA state, the latter of which conflicts with ProcessStartInfo.UseShellExecute being true. Some methods require that the apartment state not be unknown. If the state is not explicitly set, when the application encounters such a method, it defaults to MTA, and once set, the apartment state cannot be changed. However, MTA causes an exception to be thrown when the operating system shell is managing the thread.
public virtual string ToString(); |
public void WaitForExit(); |
Exception Type | Condition |
---|---|
Win32Exception | The wait setting could not be accessed. |
SystemException | No process Process.Id has been set, and a Process.Handle from which the Process.Id property can be determined does not exist. -or- There is no process associated with this Process object. -or- You are attempting to call Process.WaitForExit for a process running on a remote computer. The method is available only for processes that are running on the local computer. |
This overload of Process.WaitForExit instructs the Process component to wait an infinite amount of time for the process to exit. This can cause an application to stop responding. For example, if you call System.Diagnostics.Process.CloseMainWindow (not supported on the shared source CLI) for a process that has a user interface, the request to the operating system to terminate the associated process might not be handled if the process is written to never enter its message loop.
When an associated process exits (is shut down by the operation system through a normal or abnormal termination), the system stores administrative information about the process and returns to the component that had called Process.WaitForExit. The Process component can then access the information, which includes the Process.ExitTime, by using the Process.Handle to the exited process.
Because the associated process has exited, the Process.Handle property of the component no longer points to an existing process resource. Instead, the handle can be used only to access the operating system's information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the Process.ExitTime and Process.Handle information in memory until the Process component specifically frees the resources. For this reason, any time you call Process.Start for a Process instance, call Process.Close when the associated process has terminated and you no longer need any administrative information about it. Process.Close frees the memory allocated to the exited process.
milliseconds
Exception Type | Condition |
---|---|
Win32Exception | The wait setting could not be accessed. |
SystemException | No process Process.Id has been set, and a Process.Handle from which the Process.Id property can be determined does not exist. -or- There is no process associated with this Process object. -or- You are attempting to call Process.WaitForExit for a process running on a remote computer. The method is only available for processes that are running on the local computer. |
This overload of Process.WaitForExit instructs the Process component to wait a finite amount of time for the process to exit. If the associated process does not exit by the end of the interval because the request to terminate is denied, false is returned to the calling procedure. You can specify a negative number for milliseconds, but it is treated by Process.WaitForExit as a very large positive number. If you pass zero to the method, it returns true only if the process has already exited.
When an associated process exits (is shut down by the operation system through a normal or abnormal termination), the system stores administrative information about the process and returns to the component that had called Process.WaitForExit. The Process component can then access the information, which includes the Process.ExitTime, by using the Process.Handle to the exited process.
Because the associated process has exited, the Process.Handle property of the component no longer points to an existing process resource. Instead, the handle can be used only to access the operating system's information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the Process.ExitTime and Process.Handle information in memory until the Process component specifically frees the resources. For this reason, any time you call Process.Start for a Process instance, call Process.Close when the associated process has terminated and you no longer need any administrative information about it. Process.Close frees the memory allocated to the exited process.
public event EventHandler Disposed;
|
public event EventHandler Exited;
|
Because the associated process has exited, the Process.Handle property of the component no longer points to an existing process resource. Instead, it can be used only to access the operating system's information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the Process.ExitTime and Process.Handle property information in memory until the Process component specifically frees the resources.