日期:2008-05-05  浏览次数:20508 次

The Code

We use a ListView control in our application to display process information. The InitializeListView method adds column headers, their names and sizes to the ListView control. We'll see this method in a moment.


A row in a ListView control is represented as a ListViewItem. To add a row to the ListView, we need to create an object of a ListViewItem class, call the ListView.Items.Add method, and then pass ListViewItem as an argument.

// Add Item to the list view

ListViewItem item = new ListViewItem(str, 0);

listView1.Items.Add(item);

InitializeListView() Method

This method adds column headers, names, and sizes, and sets other column properties. The Add method of ListViewColumnCollection adds a column header to the control. This method takes the name of the column, the size, and the alignment as arguments.

// Initializes ListView

private void InitializeListView()

{

   // Add ListView Column Headers

   listView1.Columns.Add("Process", 70, HorizontalAlignment.Left);

   listView1.Columns.Add("Proc ID", 70, HorizontalAlignment.Left);

   listView1.Columns.Add("Priority", 70, HorizontalAlignment.Left);

   listView1.Columns.Add("Physical Mem(KB)", 90, HorizontalAlignment.Left);

   listView1.Columns.Add("Virtual Mem(KB)", 90, HorizontalAlignment.Left);

   listView1.Columns.Add("Start Time", 150, HorizontalAlignment.Left);

}

FillThreadView() Method

The FillThreadView method is the method that reads all the processes, and fills the list box with process information.

// Initializes ListView

private void FillThreadView()

{

   string [] str = new String[6];

   // Get all the running processes on the system

   procs = Process.GetProcesses();

   nProcessCount = procs.Length;

   textBox1.Text = nProcessCount.ToString();



   foreach(Process proc in procs)

   {

      // Physical Mem in KB

long physicalMem = proc.WorkingSet/1024;

      long virtualMem = proc.VirtualMemorySize/1024;

      str[0] = proc.ProcessName.ToString();

      str[1] = proc.Id.ToString();

      str[2] = proc.BasePriority.ToString();

      str[3] = physicalMem.ToString();

      str[4] = virtualMem.ToString();

      str[5] = proc.StartTime.ToString();



   // Add Item to the list view

      ListViewItem item = new ListViewItem(str, 0);

      listView1.Items.Add(item);

   }

}

Start Button

The Start Process button let us browse our machine directory, and pick an .exe program we want to launch. Here we use Process.Start(filename) to start a process.

// Start Process

private void button1_Click(object sender, System.EventArgs e)

{

   OpenFileDialog fdlg = new OpenFileDialog();

   fdlg.Title = "Open a Program" ;

  &