First to Start
If 'application1.exe' is always the first to start, then you could try killing the lowest PID. I believe PIDs are always assigned sequentially, so the lowest number would be the first that was opened.
So something like:
Process[] pr = Process.GetProcessesByName("MAPPOINT");
// check edgecase - no application open with this name...
if (pr.Length < 0) { return; }
//edgecase - give a default value
int firstPID= pr[0].Id;
//iterate through to find lowest number PID
foreach(Process prs in pr)
{
if (prs.Id < firstPID)
{
firstPID= prs.Id;
}
}
// close the first (aka lowest) PID
Process process = Process.GetProcessById(firstPID);
process.Kill();
If you need to be careful and only close if there are 3 or more application instances running, then put it in a function and check the length:
private static void CloseFirstInstance_IfMoreThanThree()
{
Process[] pr = Process.GetProcessesByName("MAPPOINT");
// check edgecase - no application open with this name...
if (pr.Length < 0) { return; }
//edgecase - not enough applicaitons open
if (pr.Length < 3) { return; }
//edgecase - give a default value
int firstPID = pr[0].Id;
...
}
Alternates
If the instance you want to kill is not the first to start, you may need to get fancy and:
- Ask the user to select the window, then grab the pointer to the window, then grab the PID. (Getting more difficult - UI windows have been a pain for me.)
- Actually might be simpler: you might try
PID = Process.GetProcessesByName(MyProcessName).FirstOrDefault().Id;
and kill that process. This could be all you need.