(Print this page)

The Process component
Published date: Monday, December 1, 2003
On: Moer and Éric Moreau's web site

This month column will cover the Process class that is part of the System.Diagnostics namespace. It allows you to start, stop and query processes on your own PC. It also allows you to query processes on remote computers (as long as they are running Windows platforms).

Just like when you run an application that is physically on a remote computer from the Windows Explorer, the application will run locally on your computer. The Process component will do the same if you start a process that resides on another computer. Notice that some privileges are required in order to stop or query processes.

First thing comes first

For the sake of clarity of your code, you better import the related namespace right at the beginning of your file (just before the declaration of your class) by adding this line:

Imports System.Diagnostics

Creating an instance - The easy way

If you look under the Components tab of the toolbox, you will see the Process components that you can place on a form. From the Properties panel, you can then set the StartInfo property but I won't use this way! I prefer to do it by code.

The remaining of this article will then use code to create instances of the Process component. Notice that once the instance is created, there are no differences between the two kinds of instantiation.

Creating an instance - The hard way

As you will see, creating an instance of the Process component isn't really hard! So to do it, add the following line near the top of your class (all the following samples will use this variable):

Dim MyProcess As New Process

Starting a Process

The first thing you might want to try when playing with the Process component is to start a process (what else!). The Process component exposes a StartInfo property, which includes many members itself about the process you want to start such as the name of the executable, the arguments, the WorkingDirectory, and more. After you set required information, you will be able to start the process like shown in the example below. This example starts the Notepad process opening a file called Test.txt that exists in the Temp folder of the C drive:

MyProcess.StartInfo.FileName = "notepad.exe"
MyProcess.StartInfo.WorkingDirectory = "c:\temp"
MyProcess.StartInfo.Arguments = "Test.txt"
MyProcess.Start()
This example could also have been called using this much shorter version that bypasses the StartInfo property that is not always required to use:
MyProcess.Start("notepad.exe", "c:\temp\test.txt")
You can also decide the WindowStyle (Maximized, Minimized, Normal, or Hidden) of the process that will start using this line:
MyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized
Starting a process this way won't wait for it to end before continuing with your application. Continue to read to know how to wait for a process to end.

Starting the Process that is associated with a file extension

Do you remember the VB6 ShellExecute API call that we used to open the application associated with a file extension? The Process component now encapsulates this great feature.

MyProcess.StartInfo.FileName = "c:\temp\test.doc"
MyProcess.StartInfo.UseShellExecute = True
MyProcess.Start()
The magic here is the UseShellExecute member that is set to True. Also notice that the filename to open is passed to the FileName member (and not to the Arguments member).

What if the file is not associated? An exception could be raised or you can ask Windows to display its standard dialog that will let the user associate the extension to the application he/she wants simply by adding these two lines somewhere before calling the Start method:

MyProcess.StartInfo.ErrorDialog = True
MyProcess.StartInfo.ErrorDialogParentHandle = Me.Handle

Wait for a launched process to end

This is a very frequent requirement. You want to start a process from your application, let it do its task and close, all this while your application is waiting for the launched process to stop before continuing.

As you will soon discover, the Process component makes it really (once again) simple!

Using the same code we already used to start the Notepad, we can simply add the call to the WaitForExit method to wait for the process to close before continuing (displaying the message box in my sample):

MyProcess.StartInfo.FileName = "notepad.exe"
MyProcess.StartInfo.WorkingDirectory = "c:\temp"
MyProcess.StartInfo.Arguments = "Test.txt"
MyProcess.Start()

MyProcess.WaitForExit()
MessageBox.Show("It was time!!!", "Process has now exited")
There is an overload to the WaitForExit method that accepts a number of milliseconds to wait. I strongly recommend that you look at this alternative because we never know if the process will be launched and closed correctly!

Stopping a process

If you have sufficient privileges, you can stop processes that are running. You can do it using the CloseMainWindow method or by calling the Kill method. The rule to determine which method to use is the following: you should always try the CloseMainWindow method if the process is responding. This method will close the process the correct way while the Kill method will abruptly terminates it. But how would you know if the process is responding or not? The answer is simple. Ask the Process component! It exposes a Responding property that returns a Boolean indicating the state. Here is a sample of how to use it:

MyProcess.StartInfo.FileName = "notepad.exe"
MyProcess.StartInfo.WorkingDirectory = "c:\temp"
MyProcess.StartInfo.Arguments = "Test.txt"
MyProcess.Start()

If MyProcess.Responding Then
    MyProcess.CloseMainWindow()
Else
    MyProcess.Kill()
End If

Printing a document

Another cool feature of the VB6 ShellExecute API call is the parameter that lets you print a document without doing much (using the "print" argument). The Process method gives you this feature as well.

MyProcess.StartInfo.FileName = "c:\temp\test.doc"
MyProcess.StartInfo.Verb = "Print"
MyProcess.Start()

Querying running processes for information

Ever wandered how the Task Manager displays the processes? Ever want to programmatically spy theses processes? Again, the Process component will help you with either your local PC or any remote PC on which you have sufficient privileges.

This is the code you may want to use to fill a listbox control with all the name of the processes that are running on your PC (check the overloads of the GetProcesses method for remote computer):

lstProcesses.Items.Clear()
lstProcesses.DisplayMember = "ProcessName"

For Each MyProcess In Process.GetProcesses()
    lstProcesses.Items.Add(MyProcess)
Next
Once the listbox is filled, closing/killing an application is relatively easy. See this code:
MyProcess = CType(lstProcesses.SelectedItem, Process)
If MyProcess.Responding Then
    MyProcess.CloseMainWindow()
Else
    MyProcess.Kill()
End If
You simply need to cast the selected item of the listbox and voilà!

But there are much more things to do then simply closing a process. You can change its priority, query memory footprint, processor usage, start and exit information, query modules in used by a process (could be fun to know what's in svchost!) and more. Check your documentation for the "Process Members" for more information.

Conclusion

As you've seen, the Process component helps you accomplish tasks such as starting a process, stopping it, waiting for it, …, really easily. Sure you can add complexity when you start playing with the processes you are querying to get more information but the basis are again quite simple.

I hope you appreciated the topic and see you next month.


(Print this page)