gpt4 book ai didi

c# - 由 Process Start 启动的进程的进程 ID

转载 作者:行者123 更新时间:2023-11-30 17:43:47 27 4
gpt4 key购买 nike

我试图通过进程启动时保存的进程 ID 终止进程。但是当我试图从代码后面杀死进程时,我正在捕获的进程 ID 不存在。

下面是启动进程并捕获进程 ID 的代码。

private List<int> pids = new List<int>();
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
pids.Clear();
Process myprocess= new Process();

myprocess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe");
myprocess.StartInfo.Arguments = "C:\\rdp\\RemoteIn.rdp";
myprocess.Start();
pids.Add(myprocess.Id);
}

private void terminateAll()
{
//foreach (var p in pids) p.Kill();

foreach (var i in pids)
{
Process p = Process.GetProcessById(i);
p.Kill();

}
}

private void button2_Click(object sender, EventArgs e)
{
terminateAll();
}

当我单击按钮终止进程时,它显示以下错误。

enter image description here

有什么办法可以解决这个问题。

使用 Palani Kumar 代码后,我遇到异常。 enter image description here

表单看起来像这样

enter image description here

最佳答案

我不知道为什么你的 pids 被声明为 List<int>并清除按钮单击事件中的列表 ( pids.Clear();)。无论如何,下面的内容也适用于创建多个进程。

编辑:到目前为止与 Amrit 讨论过。 Windows 8 为连接相同域的 mstsc 创建子进程。所以我稍微修改了我的代码。

    private void button1_Click(object sender, EventArgs e)
{
//pids.Clear();
Process myprocess = new Process();

myprocess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\syswow64\mstsc.exe");
myprocess.StartInfo.Arguments = "C:\\rdp\\RemoteIn.rdp";
myprocess.Start();
Thread.Sleep(100);
/* Edit */
Process proc = Process.GetProcessesByName("mstsc").FirstOrDefault(x => !pids.Any(y => y == x.Id));
if(proc != null)
{
pids.Add(proc.Id);
}
}

    private void terminateAll()
{
foreach (var i in pids)
{
try
{
Process p = Process.GetProcessById(i);
p.Kill();
}
catch (Exception ex)
{
//throw exception if we close the mstsc manually
}
}
}

关于c# - 由 Process Start 启动的进程的进程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com