3

Is there any way to determine if process was invoked by current application? I'm opening and Excel Interop process, handling files, etc, and after that I want to close only this Excel process which I've invoked.

Something like this:

Process[] pProcess = System.Diagnostics.Process.GetProcessesByName("Excel");
                foreach (var process in pProcess)
                {
                    if (process.Parent == "MyApp.exe") process.Kill();
                }
Darj
  • 1,403
  • 1
  • 17
  • 47
  • 2
    You could keep a reference to the Interop objects and close them when you wish. – Ryan Amies Jun 08 '12 at 13:10
  • 2
    Take a look at [this][1] post. It's working and will do. [1]: http://stackoverflow.com/questions/394816/how-to-get-parent-process-in-net-in-managed-way – t3hn00b Jun 08 '12 at 13:12
  • @t3hn00b for future reference, use [ text-to-display ] ( link ) – default Jun 08 '12 at 13:29
  • @Default well it was intended as an answer but there's some sort of "generic answer" protection system and my answer became a comment – t3hn00b Jun 08 '12 at 13:55
  • @t3hn00b did not know that. But now I do (and knowing is half the battle!) – default Jun 08 '12 at 15:51

2 Answers2

0

Usage:

Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id);

Code:

public static class ProcessExtensions {
private static string FindIndexedProcessName(int pid) {
    var processName = Process.GetProcessById(pid).ProcessName;
    var processesByName = Process.GetProcessesByName(processName);
    string processIndexdName = null;

    for (var index = 0; index < processesByName.Length; index++) {
        processIndexdName = index == 0 ? processName : processName + "#" + index;
        var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
        if ((int) processId.NextValue() == pid) {
            return processIndexdName;
        }
    }

    return processIndexdName;
}

private static Process FindPidFromIndexedProcessName(string indexedProcessName) {
    var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
    return Process.GetProcessById((int) parentId.NextValue());
}

public static Process Parent(this Process process) {
    return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}

Source: https://stackoverflow.com/a/2336322/706867

Community
  • 1
  • 1
Darj
  • 1,403
  • 1
  • 17
  • 47
-1

you can hold a reference to the Excel-Interop-Process and kill it if you've done what you want to...

Look at this example:

static void Main(string[] args)
    {
        var excelApp = new Microsoft.Office.Interop.Excel.Application();
        var workbook = excelApp.Workbooks.Open(Filename: @"someexcelworkbook.xls");
        workbook.Activate();
        excelApp.Visible = true;
        excelApp.Quit();
    }

Hope this is helpfull.. ;-)