C# 如何使用复选框将新进程添加到进程列表中



我正在为清理实用程序编写一个 Windows 窗体应用程序,其中 Windows 窗体应用程序将执行具有相同进程属性的多个批处理文件来清理计算机的各个部分,这就是我到目前为止所拥有的,

ProcessStartInfo[] infos = new ProcessStartInfo[]
{
new ProcessStartInfo(Environment.CurrentDirectory + @"example batch file 1"),
new ProcessStartInfo(Environment.CurrentDirectory + @"example batch file 2"),
};

然后我用,

Process[] startedProcesses = StartProcesses(infos, true);

每个进程的属性都包含在其中,

public Process[] StartProcesses(ProcessStartInfo[] infos, bool waitForExit)
{
ArrayList processesBuffer = new ArrayList();
foreach (ProcessStartInfo info in infos)
{
Process process = Process.Start(info);
if (waitForExit)
{
process.StartInfo.UseShellExecute = true;
process.StartInfo.Verb = "runas";
process.WaitForExit();
}
}
}

问题是,我想使用 if 语句将新的批处理文件添加到列表中,因为我希望用户使用复选框控制执行哪些批处理文件,例如,

ProcessStartInfo[] infos = new ProcessStartInfo[]
{
if (checkedListBox1.GetItemCheckState(0) == CheckState.Checked)
{
new ProcessStartInfo(Environment.CurrentDirectory + @"example batch file 1"),
}
if (checkedListBox1.GetItemCheckState(1) == CheckState.Checked)
{
new ProcessStartInfo(Environment.CurrentDirectory + @"example batch file 2"),
}
};

但这行不通...这周围有没有?

亲切的问候,雅各布

在上一个代码片段中,您遇到了语法错误,因为这不是填充数组的正确方法。我修改了它,所以它是一个简单的例子并使用了一个列表。它根据选中的项目启动应用程序。您应该准确显示您遇到了哪些错误。

private void button1_Click(object sender, EventArgs e)
{
List<ProcessStartInfo> startInfos = new List<ProcessStartInfo>();
if (checkedListBox1.GetItemChecked(0))
{
startInfos.Add(new ProcessStartInfo("notepad.exe"));
}
if (checkedListBox1.GetItemChecked(1))
{
startInfos.Add(new ProcessStartInfo("calc.exe"));
}
if (checkedListBox1.GetItemChecked(2))
{
startInfos.Add(new ProcessStartInfo("explorer.exe"));
}
foreach (var startInfo in startInfos)
{
Process.Start(startInfo);
}
}

最新更新