Free mag vol1 | Page 685

CHAPTER 17  PROCESSES, APPDOMAINS, AND OBJECT CONTEXTS Enumerating Running Processes To illustrate the process of manipulating Process objects (pardon the redundancy), assume you have a C# Console Application named ProcessManipulator that defines the following static helper method within the Program class (be sure you import the System.Diagnostics namespace in your code file): static void ListAllRunningProcesses() { // Get all the processes on the local machine, ordered by // PID. var runningProcs = from proc in Process.GetProcesses(".") orderby proc.Id select proc; // Print out PID and name of each process. foreach(var p in runningProcs) { string info = string.Format("-> PID: {0}\tName: {1}", p.Id, p.ProcessName); Console.WriteLine(info); } Console.WriteLine("************************************\n"); } The static Process.GetProcesses() method returns an array of Process objects that represent the running processes on the target machine (the dot notation shown here represents the local computer). After you have obtained the array of Process objects, you are able to invoke any of the members seen in Tables 17-2 and 17-3. Here, you are simply displaying the PID and the name of each process, ordered by PID. Assuming the Main() method has been updated to call ListAllRunningProcesses() as follows: static void Main(string[] args) { Console.WriteLine("***** Fun with Processes *****\n"); ListAllRunningProcesses(); Console.ReadLine(); } you will see the names and PIDs for all processes on your local computer. Here is some partial output from my current machine: ***** Fun with Processes ***** -> -> -> -> -> -> -> -> -> -> -> 628 PID: PID: PID: PID: PID: PID: PID: PID: PID: PID: PID: 0 4 108 268 432 448 472 504 536 560 584 Name: Name: Name: Name: Name: Name: Name: Name: Name: Name: Name: Idle System iexplore smss csrss svchost wininit csrss winlogon services lsass