简体   繁体   中英

Getting a specific process of task manager in c#

I have to 2 list box, the other one is for getting the specific process(I listed it in like chrome, mspaint, notepad etc.) when these programs are running my label color would go green and when one of these programs closes label would go red follow by the name of the program that was close. My problem is I can't specify the closed program all it does it when I close any program my label always go red.

Here's my code:

private void running_process()
{
    Process[] processes = Process.GetProcesses("PCNAME");

    foreach (Process p in processes)
    {
        foreach (string item in listBox2.Items)
        {
            if (item == p.ProcessName)
            {
                listBox1.Items.Add(p.ProcessName);
            }
            if (listBox1.Items.Contains(item))
                label4.BackColor = Color.Green;
            else

                label4.BackColor = Color.Red;
        }
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    listBox1.Items.Clear();
    running_process();
}

private void button2_Click(object sender, EventArgs e)
{
    timer1.Enabled = true;
}

The problem with your code is that you setting label4.BackColor for every iteration, thus it would keep only the value for the last one. So if your last process in listBox2 is in listBox1 then the label should be green and if no - then red.

I am not sure if I get your requirement correctly (in terms of listBox1) but if you want it to keep processes that are running AND listed in the listBox2 (as it is in your code) then this should work:

label4.BackColor = Color.Green; //by default the label color is Green
foreach (string item in listBox2.Items)
{
    var processDeleted = true; //and by default we suppose that every process was deleted
    foreach (var process in processes)
    {
        if (process.ProcessName == item)
        {
            listBox1.Items.Add(process.ProcessName);
            processDeleted = false;
        }
    }
    if (processDeleted) label4.BackColor = Color.Red;
}

But that way you can get a big list of similar entries in the listBox1, so I would write something like:

label4.BackColor = Color.Green;
foreach (string item in listBox2.Items)
{
    if (processes.Any(x => x.ProcessName == item))
        listBox1.Items.Add(item);
    else
        label4.BackColor = Color.Red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM