【问题标题】:Problem Process.GetProcesses Not work with 2 same processes问题 Process.GetProcesses 不适用于 2 个相同的进程
【发布时间】:2021-06-05 11:47:25
【问题描述】:

如果我使用 Process.GetProcesses();我应该显示所有本地进程还是? 我的问题是我想调用所有“引擎”进程。为此,我启动了程序 2x,但在我的列表框中我只得到了一次。 有人能告诉我为什么吗? 附上2x“引擎”的代码和任务管理器截图。

private void button1_Click(object sender, EventArgs e)
{
    {
        listBox1.Items.Clear();

        Process[] localAll = Process.GetProcesses();
        
        listBox1.BeginUpdate();

        for (int i = 0; i <= 49; i++)
        {
            string Prozess = Convert.ToString(localAll[i]);
            bool b = Prozess.Contains(textBox1.Text);
            if (b)
            {
                listBox1.Items.Add(Prozess);
            }
        }

        listBox1.EndUpdate();
    }
}

问候

提姆

【问题讨论】:

标签: c# visual-studio


【解决方案1】:

回答主要问题,原因可能在i &lt;= 49 条件下。 Process.GetProcesses() 检索到的进程列表未排序,因此其中的进程随机定位,前 50 个元素可能不包括您的第二个/第三个/N 个进程实例,甚至不包括指定的一个。 您应该检查整个列表,而不是只检查 50 个。

另外, 您的localAll[i]Process 的对象,其中包含ProcessName 属性(以及有关运行进程的其他信息)。您试图检查 Processan object 是否在其字符串表示中(由 Convert.ToString() 提供)(它为您提供 System.Diagnostics.Process (ProcessName) 类型名称)是否包含来自您的 textBox1 的字符串值。

string someInput = textBox1.Text;

Process[] processes = Process.GetProcesses();

// Try also change i <= 49 to a collection.Count/Length, 
// because received by Process.GetProcesses() list of processes
// isn't sorted and your duplicated processes may not be included
// in first 50 elements.
for (int i = 0; i < processes.Length; ++i) // or foreach (Process p in processes) ...
{                
    string processName = processes[i].ProcessName    
    // Do whatever you wish with processName

    if (processName.Contains(someInput))
    {
        // listBox1.Items.Add(processName + ".exe");
        // ProcessName property doesn't include extension ".exe", 
        // only executable binary name.
    }
}

或者简单地使用System.Linq 扩展:

string[] processes = Process.GetProcesses().
                     Where(x => x.ProcessName.Contains(textBox1.Text)). // Take care about case-sensivity of comparsion
                     Select(x => x.ProcessName + ".exe").
                     ToArray();
// Where extension will filtrate all running processes
// by checking its ProcessName properties for containing
// your specified input value in textBox1
// Select extension will retrieve only process names
// from filtrated Process objects collection as strings, 
// which you can convert to an array of strings.

// Simply append all filtrated string collection to your ListBox by AddRange.
listBox1.Items.AddRange(processes);

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2010-11-01
    • 2021-08-09
    • 1970-01-01
    • 2018-09-01
    • 2019-10-09
    相关资源
    最近更新 更多