2011-12-13 56 views
6

我正在用c#创建一个excel应用程序。 因为我会保持紧急的excel文件,我想保持它的处理程序打开。 我想保留excel进程ID,这样我就可以杀死它,以防系统崩溃。获取Excel应用程序进程号

创建时如何获得Excel Pid?

+0

你就可以开始告诉我们如何创建/打开Excel ?请显示一些代码 –

+1

你需要什么PID的?你可以自己发布Com对象 – Shai

回答

-2

这里有一个如何打开使用Excel的互操作一个Excel文件,并妥善处理实例 (来源:谷歌)为例

Application ExcelObj = new Application(); 
    Workbook WB = ExcelObj.Workbooks.Open(fileName, 
     0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", 
     false, false, 0, true, false, false); 
    Sheets sheets = WB.Worksheets; 
    Worksheet WS = (Worksheet)sheets.get_Item(1); 
    Range excelRange = WS.UsedRange; 

     ... (DO STUFF?) 

     // Get rid of everything - close Excel 
     while (Marshal.ReleaseComObject(WB) > 0) { } 
     WB = null; 
     while (Marshal.ReleaseComObject(sheets) > 0) { } 
     sheets = null; 
     while (Marshal.ReleaseComObject(WS) > 0) { } 
     WS = null; 
     while (Marshal.ReleaseComObject(excelRange) > 0) { } 
     excelRange = null; 
     GC(); 
     ExcelObj.Quit(); 
     while (Marshal.ReleaseComObject(ExcelObj) > 0) { } 
     ExcelObj = null; 
     GC(); 

    public static void GC() 
    { 
     System.GC.Collect(); 
     System.GC.WaitForPendingFinalizers(); 
     System.GC.Collect(); 
     System.GC.WaitForPendingFinalizers(); 
    } 
+0

为什么downvote?只是好奇.. – abhilash

+0

击败我!此代码示例是100%正常工作... – Shai

+0

可能是downvoted,因为它不回答问题!如果Excel出去吃午餐,它经常做的事情,释放你所有的参考是不会杀死它的。你需要进程ID。 –

22
using Excel = Microsoft.Office.Interop.Excel; 
using System.Runtime.InteropServices; 
using System.Diagnostics; 

class Sample 
{ 
    [DllImport("user32.dll")] 
    static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId); 

    Process GetExcelProcess(Excel.Application excelApp) 
    { 
     int id; 
     GetWindowThreadProcessId(excelApp.Hwnd, out id); 
     return Process.GetProcessById(id); 
    } 
} 
+0

很好,谢谢! – Belial09

相关问题