My situation is that I'm developing a C# application which is launching an instance of a Microsoft Office Excel Application.
I change some of the Form's functions so that the instantiated Excel Application is being killed and cleaned up from memory when my Form's being closed.
What I want to do is to perform the opposite. I'd like my instance of Excel to close my windows Form when it's being exited.
Ok, I haven't even tried this so I'm not sure if it will work, but you could try something along these lines:
UPDATE
Try the following code (its not pretty):
The problem when working with an Excel Application is that even if the user closes it's main window, the process will keep on running in the background. In order to release it completely you have to call
Application.Quit
but you should only do that when you detect the user closing the window which is exactly the problem you are trying to solve...you have a circular reference here :DLatching to the relevant
System.Diagnostics.Process
doesn't seem to work either, as theExited
event never gets fired (not even if you terminate the background process from the task manager). My guess is that this event is fired only with processes launched throughprocess = Process.Start(...)
.So the only solution I can see is polling if Excel`s main window is visible. Once it is not, that probably means the user closed the main window and the Excel application should be terminated (if there is some scenario where Excel's main window's visibility can be false other than when the user wants to terminate the process then this solution is not valid). From there it is pretty straightforward.
This is what i did for the same scenario.
I created a process within the class
Then a delegate to method which closes the app
Setting the delegate to the app closing method
This below code is written inside the button click event This opens the excel. Here subscribe for the Exited event of the process
On clicking close button of the excel, this method will be called
This will close the app.
Hope this helps
Your first try would have worked, just needed to enavle raising of events for the process, this is what I did to catch a launched visio exit or crash.