Reputation: 16138
I am writing a small program which will open Word, Excel or Powerpoint files, inspect the files without doing any modifications and then quit the respective application again. E.g. for Word this looks like follows and works fine for normal documents:
s_word.Quit(false);
Marshal.ReleaseComObject(s_word);
s_word = null;
GC.Collect();
GC.WaitForPendingFinalizers();
I also have a timer which should quit the application if it does not quit after x seconds. However, I have a problem if any dialog etc. pops up, e.g. a password prompt when opening the document. I will run into my timeout but all the commands above won't quit the app then. So I added a hard process kill method which will simply look for all WINWORD process and kill them. While this works, there are some pitfalls to this I'd like to avoid. For example the next time you will open the failed document, Word will ask you whether to repair it etc.
So, is there any better way to force an Office application to quit?
Upvotes: 2
Views: 620
Reputation: 1971
I have created an extremely naive snippet that should allow you to get the process of the Office program instance you just started but will leave others untouched. You can then call processInstance.Kill() to end it.
Process[] oldRunningWordInstances = Process.GetProcessesByName("Microsoft Word");
Word.Application application = new Word.Application();
Process[] newRunningWordInstances = Process.GetProcessesByName("Microsoft Word");
Process applicationProcess = null;
foreach (Process p in newRunningWordInstances)
if (!oldRunningWordInstances.Contains(p))
{
applicationProcess = p;
break;
}
applicationProcess.Kill();
This method to acquire the process(id) is unreliable in theory. There might be better solutions to acquire the process.
Upvotes: 2