C#:如何查找当前应用程序是否调用了进程?

时间:2012-06-08 13:04:31

标签: c# excel process interop child-process

有没有办法确定当前应用程序是否调用了进程?我正在打开和Excel Interop进程,处理文件等,之后我想只关闭我调用的这个Excel进程。

这样的事情:

Process[] pProcess = System.Diagnostics.Process.GetProcessesByName("Excel");
                foreach (var process in pProcess)
                {
                    if (process.Parent == "MyApp.exe") process.Kill();
                }

2 个答案:

答案 0 :(得分:0)

用法:

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

代码:

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));
}
}

来源:https://stackoverflow.com/a/2336322/706867

答案 1 :(得分:-1)

你可以保留对Excel-Interop-Process的引用,如果你已经完成了你想做的事情就把它杀掉......

看看这个例子:

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();
    }

希望这有用..; - )