Working with the System.Diagnostic.Process Class Introduction The System.Diagnostic.Process class is used for the starting and stopping of processes; and controlling and monitoring application. With this powerful class you can gain access to information and use it to create an instance of an application or stop a running process. This FAQ will cover how to get a list of running process and how to start a new process by calling an executable or a register file extension (like .doc). Why would you want to use the Process class? This class is the "Successor" to the Shell command in VB6. If you need to start an application with parameters, or get notified when it exits, this class provides the power and information you need. Note: All code provide assumes that you have the Imported the System.Diagnostics namespace. The simplest way to do this is to add the following line of code at the top of your file. Also, for the code posted in this FAQ output is dumped to the Output window using the Debug.WriteLine method. Code: Imports System.Diagnostics Getting Information Getting information from the current process. It's important to find out what information we can obtain from a Process, so let's take a look at the information available. This example will be using the GetCurrentProcess to retrieve a reference to the applications process component. To do this we will declare a variable and use the shared GetCurrentProcess method to retrieve the object reference. All further code in the section will build on this declaration. Code: Dim proc As Process = Process.GetCurrentProcess Now that we have a reference to our Process, let's find out what information it can tell us. There is a lot of information you can retrieve from a Process Object. Here are just a few of them. Code: ' Unique identifier for this process. Debug.WriteLine(proc.Id.ToString) ' Name of the process. Debug.WriteLine(proc.ProcessName) ' This process's native handle. Debug.WriteLine(proc.Handle.ToString) ' Caption of the main window. Debug.WriteLine(proc.MainWindowTitle) ' Window handle of the main window Debug.WriteLine(proc.MainWindowHandle) ' Base Priority Information. Debug.WriteLine(proc.BasePriority.ToString) ' Overall priority category Debug.WriteLine(proc.PriorityClass.ToString) ' Number of handles this process has opened. Debug.WriteLine(proc.HandleCount.ToString) ' Indicates whether the user interface of this process is responding. Debug.WriteLine(proc.Responding.ToString) There are more properties available including information on Processor and Memory usage. Getting a list of the Current Processes Getting a list of the current processes running on your system is an easy task. We can use the shared method GetProcesses() to retrieve this information. The GetProcesses() method returns an Array of Process components that we can further query to learn more about any given process. Code: ' Declare a Process class. Dim proc As Process ' Loop through the Processes and write the name of the Process to the output window. For each proc In Process.GetProcesses Debug.Writeline(proc.ProcessName) Next Starting a Process Starting a Process with the Shared Start method. Starting a Process is a manner of knowing what the path to the executable (or other object that can be started through the run command). The simplest way to do this is to use the Shared Start method of the Process class. This example will be using notepad.exe and a text file named info.txt. Code: ' Start an instance of Notepad. Process.Start("notepad.exe") ' Start an instance of Notepad and open the info.txt file. Process.Start("notepad.exe", "c:\info.txt") ' Start an instance of the application that is registered to txt files. ' Just like you would double-click a file in Windows Explorer. Process.Start("c:\info.txt") On most systems, the "txt" extension is registered to the Notepad application. This will start a new instance of Notepad and open the info.txt file. These shared methods offer a way to create a process, but if we need more control over the process we need to create an instance of the Process class itself and use the StartInfo object. Also the shared method will throw an error if we pass a file that is not registered with the system. Starting a Process using the Process Class and the StartInfo object. Starting a process using the StartInfo object is relatively easy. The only required property is StartInfo.FileName which is a string specifying what to start. So why would you use it. Simple, you can provide error handling if a file is not registered and specify the WindowStyle. Also creating an instance of the Process Class allows for notification when the process has exited through events. Below we will start notepad again and pass it the argument of "C:\info.txt" Code: ' Create an Instance of the Process Class Dim proc As New Process ' Provide the name of the application or file. proc.StartInfo.FileName = "notepad.exe" ' Specify the arguments. proc.StartInfo.Arguments = "c:\info.txt" ' Start the process. proc.Start Simple, right? Good. Using Events to find out when a process has Exited. The process class exposes two events; Disposed and Exited. Disposed is inherited from Component, Exited occurs when the process exits. First we need to create an event handler that will execute when the process exits. In our event handler, we will write the ExitCode and ExitTime properties to the output window. Code: Private Sub OnProcessExit(ByVal sender As Object, ByVal e As EventArgs) ' Avoid late binding and Cast the Object to a Process. Dim proc As Process = CType(sender, Process) ' Write the ExitCode Debug.WriteLine(proc.ExitCode) ' Write the ExitTime Debug.WriteLine(proc.ExitTime.ToString) End Sub So now we have an event handler, but how do we get the event handler to fire? To do this we must add two lines of code before we start our process. We need to set EnableRaisingEvents to True in order for the events to fire. We must also add an event handler to trap the Exited event and run our OnProcessExit method. Code: Dim proc As New Process ' Provide the name of the application or file. proc.StartInfo.FileName = "notepad.exe" ' Specify the arguments. proc.StartInfo.Arguments = "c:\info.txt" ' This will allow the Exited event to fire. proc.EnableRaisingEvents = True ' Add an event handler for this process. ' Run the OnProcessExit sub when this process exits. AddHandler proc.Exited, AddressOf OnProcessExit ' Start the process. proc.Start() Now when the process exits, the Exited Event will be raised and our OnProcessExit method will be called. Providing Error Handling Providing error handling is a crucial part of any application. With the process method you will want to catch any error that is raised. The most common error is a file not found, the second most common error is dealing with files that are not registered to any particular application. You can proactively avoid "file not found" errors by using the Shared Exists method of the System.IO.File class. We will use this later when we put everything together to create our StartProcess Method. Code: If System.IO.File.Exists(path) = False Then Exit Sub End If Dealing with files that are not registered in the system is a little different. When you use Windows Explorer and try to open a file that is not registered, you are prompted with the "Open With" dialog and can then choose the application to open the file with. This functionality is provided by the Process class by setting the ErrorDialog Property in the StartInfo object to True. Code: proc.StartInfo.ErrorDialog = True Putting it all together Now that we have an understanding of the Process component and some of the things we can do, I am going to share two methods that I use for starting a Process. Code: ' Method to Start a Process with Error Handling. Private Sub StartProcess(ByVal Path As String) ' Declare the Process variable. Dim proc As Process ' Ensure that the file exists If System.IO.File.Exists(Path) = False Then Exit Sub End If ' Create the Process component. proc = New Process ' Set EnableRaisingEvents to True. proc.EnableRaisingEvents = True ' Add an event handler to trap the Exited event. AddHandler proc.Exited, AddressOf OnProcessExit ' Build the StartInfo object. ' Set the FileName property to the argument that was passed. proc.StartInfo.FileName = Path ' Enable the ErrorDialog. proc.StartInfo.ErrorDialog = True ' Start the Process proc.Start() End Sub ' Event Handler for Process.Exited Event Private Sub OnProcessExit(ByVal sender As Object, ByVal e As EventArgs) ' Avoid late binding and cast the Object to a specific Process component. Dim proc As Process = CType(sender, Process) ' Write out the Exit information. Debug.WriteLine(proc.ExitCode) Debug.WriteLine(proc.ExitTime) ' Dispose and Clear the object. proc.Dispose() proc = Nothing End Sub source: http://vbcity.com/forums/topic.asp?tid=29605 |
Sep 18, 2007
Working with the System.Diagnostic.Process Class
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment