Hey there,
This is an issue I had for a long time aswell. I'm afraid that I did not find a solution by using the Interop. However I did create some code that killed the process automatically for me. Now I don't know if this is what you want because i found it somewhat vague but here it goes:
First we have to Import a Dll to make use of the
GetWindowThreadProcessId()
function. (Don't mind the class names it's just my code).
using System.Runtime.InteropServices;
...
public partial class Quotation : Form
{
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
...
}
Then we are going to create a variable which is going to store the processId. (I included your variable names for this)
uint processId = 0;
if (xlsApplication != null)
{
if (xlsApplication.Workbooks != null)
{
if (xlsApplication.Workbooks.Count < 0)
{
GetWindowThreadProcessId(new IntPtr(xlsApplication.Hwnd), out processId);
}
}
}
And finally the cleanup. The killing of the process needs to be inside try and catch statements. This because the closing of Excel does appear to happen sometimes.
if (xlsApplication != null)
{
if (xlsApplication.Workbooks != null)
{
if (xlsApplication.Workbooks.Count < 0)
{
xlsWorkbook.Close(true, @"C:\test.xls", null);
xlsApplication.Workbooks.Close();
xlsApplication.Quit();
missing = null;
ReleaseObjects();
r_Time = null;
r_Name = null;
r_ReceivedTime = null;
r_Received = null;
r_OrderedTime = null;
r_Ordered = null;
xlsRange = null;
xlsWorksheet = null;
xlsWorkbook = null;
xlsApplication = null;
}
}
}
try
{
if (processId != 0)
{
Process excelProcess = Process.GetProcessById((int)processId);
excelProcess.CloseMainWindow();
excelProcess.Refresh();
excelProcess.Kill();
}
}
catch
{
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
I hope this helps