我正在尝试创建一个自动关闭应用程序,当多个进程关闭时,该应用程序将关闭计算机。
示例:用户有一个清单框,列出了所有当前正在运行的进程。用户检查标记了他们希望监视的所有所需进程。一旦所有这些进程关闭,则计算机应该关闭。我在执行此操作时遇到问题,我不知道如何检查程序以查看已检查的过程项是否已关闭。这是我现在的一些代码,我将非常感谢任何人都可以给我的帮助。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int counter;
Process[] p = Process.GetProcesses();
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 100;
foreach (Process plist in p)
{
checkedListBox1.Items.Add(plist.ProcessName);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
counter = 0;
checkedListBox1.Items.Clear();
Process[] p = Process.GetProcesses();
foreach (Process plist in p)
{
checkedListBox1.Items.Add(plist.ProcessName);
counter = counter + 1;
}
if (counter == 0)
{
MessageBox.Show("works");
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
}
}
谢谢,
-Angel Mendez
答案 0 :(得分:1)
假设您有List<string>
代表您的复选框,请尝试:
List<string> checkProcs = new List<string>(); // All monitored process names
var allProcesses = Process.GetProcesses().Select(p => p.ProcessName);
// Now use:
allProcesses.Except(checkProcs)
这应该提供一个不再存在的受监视进程的列表。
答案 1 :(得分:0)
using System;
using System.Collections;
using System.Windows.Forms;
using System.Diagnostics;
namespace testprocessapp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Process[] p = Process.GetProcesses();
timer1.Interval = 10000;
checkedListBox1.Items.Clear();
foreach (Process plist in p)
{
checkedListBox1.Items.Add(plist.ProcessName);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
int counter = 0;
Process[] p = Process.GetProcesses();
foreach (Process process in p)
{
foreach (var item in checkedListBox1.Items)
{
if (item.ToString() == process.ProcessName)
{
counter = counter + 1;
}
}
}
MessageBox.Show(counter == 0 ? "Your process has been terminated" : "Your process is still there");
}
private void button1_Click(object sender, EventArgs e)
{
ArrayList arrayList = new ArrayList();
foreach (var checkedItem in checkedListBox1.CheckedItems)
{
arrayList.Add(checkedItem);
}
checkedListBox1.DataSource = arrayList;
//button1.Enabled = false;
button1.Text = "Monitoring...";
timer1.Start();
}
}
}
我现在已经创建了应用程序的副本。这段代码有效。