Recipe 14.6. List All Running Processes


Problem

You need to display a list of the processes that are currently running on the local workstation.

Solution

Sample code folder: Chapter 14\RunningProcesses

Use the System.Diagnostics.Process class to access a collection of objects representing all currently running processes.

Discussion

This recipe's sample code displays any process with a window title in a listbox. Create a new Windows Forms application, and add a ListBox control named ListBox1 to Form1. Then add the following event handler to Form1's code:

 Private Sub Form1_Load(ByVal sender As Object, _       ByVal e As System.EventArgs) Handles Me.Load    ' ----- Show all top-level processes.    For Each oneProcess As Process In Process.GetProcesses( )       If (oneProcess.MainWindowTitle <> "") Then          ListBox1.Items.Add("Program: " & _             oneProcess.MainWindowTitle)       Else          ListBox1.Items.Add("Process: " & _             oneProcess.ProcessName)       End If    Next oneProcess End Sub 

Run the program to display the list of processes. It should generally match the list of processes and applications you see in the Windows Task Manager, although the form itself ("Form1") will probably not appear, since it wasn't yet visible when ListBox1 was populated. Figure 14-6 shows the running program with the listbox populated.

The System.Diagnostics.Process class includes a shared member named GetProcesses() that returns a collection of Process objects, each representing a running process. There are many more processes than just those with window titles; all running Windows services also appear in this collection.

The Process object includes many properties and methods that let you manage each process. However, your level of authorization as configured by the system administrator may prevent you from modifying or even viewing process details.

Figure 14-6. Listing all processes running on a system





Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net