I know that it is too late, but I found this topic because I had the same problem.
And my decision can help other people.
The solution above does not work well, because it killed every running instance of Word, although it was not opened by C # except the user.
So it was not friendly.
My code checks the processes before / after creating the Word.Application
object in C # and writes the WINWORD
process identifiers to the List<int>
then it compares the values ββas in the List<int>
. When processID
not found in both List<int>
, it kills the process with this identifier.
public List<int> getRunningProcesses() { List<int> ProcessIDs = new List<int>();
Run this twice (one time before creating Word.Application and one time after).
List<int> processesbeforegen = getRunningProcesses();
Then run killProcesses(processesbeforegen, processesaftergen);
private void killProcesses(List<int> processesbeforegen, List<int> processesaftergen) { foreach (int pidafter in processesaftergen) { bool processfound = false; foreach (int pidbefore in processesbeforegen) { if (pidafter == pidbefore) { processfound = true; } } if (processfound == false) { Process clsProcess = Process.GetProcessById(pidafter); clsProcess.Kill(); } } }
source share