只显示某些过程
本文关键字:过程 显示 | 更新日期: 2023-09-27 18:10:17
private void UpdateProcessList()
{
// clear the existing list of any items
listBox1.Items.Clear();
// loop through the running processes and add
//each to the list
foreach (System.Diagnostics.Process p in
System.Diagnostics.Process.GetProcesses())
{
listBox1.Items.Add(p.ProcessName + " - " + p.Id);
}
// display the number of running processes in
// a status message at the bottom of the page
listBox1.Text = "Processes running: " +
listBox1.Items.Count.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
ProcessStartInfo pi = new ProcessStartInfo();
pi.Verb = "runas";
pi.FileName = "1-AccountServer.exe";
pi.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pi);
Thread.Sleep(10000);
pi.FileName = "2-DatabaseServer.exe";
pi.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pi);
Thread.Sleep(10000);
pi.FileName = "3-CoreServer.exe";
pi.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pi);
Thread.Sleep(10000);
pi.FileName = "4-CacheServer.exe";
pi.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pi);
Thread.Sleep(10000);
pi.FileName = "5-Certifier.exe";
pi.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pi);
Thread.Sleep(10000);
pi.FileName = "6-LoginServer.exe";
pi.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pi);
Thread.Sleep(10000);
pi.FileName = "7-WorldServer.exe";
pi.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pi);
Thread.Sleep(10000);
}
问题是,我不希望每个过程都显示,但只显示这七个特定的过程,我该怎么做呢?它确实可以工作,但不是我实际想要的方式>.<我已经在互联网上搜索了一段时间,实际上找到了这段代码,并实现了我想要的,但它只是显示了这么多的过程,我想要的是毫无意义的。>
创建一个包含所有进程名的List(of String)
List<string> myProcesses = new List<string>()
{
"1-AccountServer.exe","2-DatabaseServer.exe",
"3-CoreServer.exe", "4-CacheServer.exe","5-Certifier.exe",
"6-LoginServer.exe","7-WorldServer.exe"
};
然后检查
foreach (Process p in Process.GetProcesses())
{
if(myProcesses.Contains(p.ProcessName + ".exe"))
listBox1.Items.Add(p.ProcessName + " - " + p.Id);
}
顺便说一下,创建这个列表对于构建一个启动所有进程的通用方法也有很大帮助
private void button1_Click(object sender, EventArgs e)
{
ProcessStartInfo pi = new ProcessStartInfo();
pi.Verb = "runas";
pi.WindowStyle = ProcessWindowStyle.Hidden;
foreach(string s in myProcesses)
{
pi.FileName = s;
Process.Start(pi);
Thread.Sleep(10000);
}
}
EDIT正如IV4在其评论中建议的那样,也许一种不同的方法可以将所有进程聚集在一个HashSet中,然后根据HashSet检查列表(只有7个元素),这在性能方面可能会更好
HashSet<Process> anHashOfProcesses = new HashSet<Process>(Process.GetProcesses());
foreach(string s in myProcesses)
{
var p = anHashOfProcesses.FirstOrDefault(z => z.ProcessName + ".exe" == s);
if(p != null) listBox1.Items.Add(p.ProcessName + " - " + p.Id);
}