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();
                }
Adrian K.
  • 1,383
  • 1
  • 15
  • 45

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
Adrian K.
  • 1,383
  • 1
  • 15
  • 45
-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.. ;-)