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

C# How to add new processes to a list of processes using a checkedlistbox

我正在为清理实用程序编写一个 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 语句将新的批处理文件添加到列表中,因为我希望用户使用 checkedlistbox 控制执行哪些批处理文件,例如,

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);
        }
    }