Home
Manage Your Code
Snippet: CloseExcelComObject (C#)
Title: CloseExcelComObject Language: C#
Description: Kills the ApplicationClass() object created when you use System.Office.Interlop.Excel class. Views: 996
Author: Sokol Ramaj Date Added: 9/7/2009
Copy Code  
1///Return Type: DWORD->unsigned int

2///hWnd: HWND->HWND__*

3///lpdwProcessId: LPDWORD->DWORD*

4[System.Runtime.InteropServices.DllImportAttribute( "user32.dll", EntryPoint = "GetWindowThreadProcessId" )]
5public static extern int GetWindowThreadProcessId ( [System.Runtime.InteropServices.InAttribute()] System.IntPtr hWnd, out int lpdwProcessId );
6
7
8private int _ExcelPID = 0;
9Process _ExcelProcess;
10
11private Application _ExcelApp = new ApplicationClass();
12GetWindowThreadProcessId( new IntPtr(_ExcelApp.Hwnd), out _ExcelPID );
13_ExcelProcess = System.Diagnostics.Process.GetProcessById( _ExcelPID );
14
15...
16
17_ExcelProcess.Kill();
Notes
I couldn't close the 'EXCEL' app in any other way so this is the only way i could do it. Be careful and don't forget to Release the com objects before killing the app. System.Runtime.InteropServices.Marshal.ReleaseComObject( _Workbook ); System.Runtime.InteropServices.Marshal.ReleaseComObject( _ExcelApp );