重新学C#编程155-进程与线程:进程类Process练习4-进程按照名字字符串做一下排序
在使用windows的任务管理器时候可以看到进程是可以按照进程名字进行排序的。现在做一个练习,也把进程做一下排序,顺带夫婿一下字符串的比较、listbox控件属性的操作。
在最前面加上
using System.Diagnostics;
窗体的打开事件加入下面的代码
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
Process[] process = Process.GetProcesses();
string[] strProcessName = new string[process.Length];
string strTemp;
//listbox2不排序
foreach(Process item in process)
{
listBox2.Items.Add(item.ProcessName);
}
//下面的代码做排序
for(int i=0;i<process.Length;i++)
{
strProcessName[i] = process[i].ProcessName.ToString();
}
for (int i = 0; i < process.Length - 1; i++)
{
for (int j = i + 1; j < process.Length; j++)
{
if (string.Compare(strProcessName[i], strProcessName[j]) >= 0)
{
strTemp = strProcessName[i];
strProcessName[i] = strProcessName[j];
strProcessName[j] = strTemp;
}
}
}
foreach (string item in strProcessName)
{
listBox1.Items.Add(item);
}
}
运行后效果如下


浙公网安备 33010602011771号