I am trying to kill the process by process ID which I am saving when the process start. But the process ID which I am capturing doesn't exists when I try to kill the process from code behind.
This is the code below to start the process and capture the process 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();
}
When I click button to terminate the process it shows following error.
Is there any way to fix this.
After using Palani Kumar code, I am getting below exception.
Form Looks like this