To kill exact Excel process used for your app at that moment firstly identify its PID by entering the below code under the saving and closing instructions in your method 1 (potentially main method):
int pid = -1;
HandleRef hwnd = new HandleRef(xlApp, (IntPtr)xlApp.Hwnd);
GetWindowThreadProcessId(hwnd, out pid);
KillProcess(pid, "EXCEL");
Additionally below the above method 1 enter this new method:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowThreadProcessId(HandleRef handle, out int processId);
static public void KillProcess(int pid, string processName)
{
// to kill current process of excel
Process[] AllProcesses = Process.GetProcessesByName(processName);
foreach (Process process in AllProcesses)
{
if (process.Id == pid)
{
process.Kill();
}
}
AllProcesses = null;
}
So all code is going to be like that in larger area view:
public CopyPaste2()
{
srcWb= @"C:\WIP\sourceWB.xlsm";
destWb= @"C:\WIP\destinationWB.xlsm";
Application xlApp = new Application();
xlApp.Visible = true;
Workbook strSrcWb= xlApp.Workbooks.Open(srcWb, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Workbook strDestWb= xlApp.Workbooks.Open(destWb, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet srcWs = strSrcWb.Worksheets.get_Item("Sheet1");
Worksheet destWs = strDestWb.Worksheets.get_Item("Sheet1");
... rest of the executive methods ...
strDestWb.Save();
strSrcWb.Close();
strDestWb.Close();
xlApp.Quit();
int pid = -1;
HandleRef hwnd = new HandleRef(xlApp, (IntPtr)xlApp.Hwnd);
GetWindowThreadProcessId(hwnd, out pid);
KillProcess(pid, "EXCEL");
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowThreadProcessId(HandleRef handle, out int processId);
static public void KillProcess(int pid, string processName)
{
// to kill current process of excel
Process[] AllProcesses = Process.GetProcessesByName(processName);
foreach (Process process in AllProcesses)
{
if (process.Id == pid)
{
process.Kill();
}
}
AllProcesses = null;
}