Proper way to detect if Excel has been quit and respond appropriately?


I have a Windows Forms app that opens an instance of Excel. If the user quits the app early, I want to make sure that this Excel instance has been quit. I tried calling the Excel instance's Quit() method if the instance was not null, like this:

static class Program
        static void Main()
            Form1 form1 = new Form1();
            if (form1.xlApp != null)

But if I quit the Excel app in Task Manager and then close the GUI, I get this error:

System.Runtime.InteropServices.COMException (0x800706BA): 
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

A check of (xlApp==null) in the Immediate window showed that xlApp was not null, even though there was no instance of Excel running.

So I tried removing the Quit() line and using this instead:


This worked fine for closing without error when the user quits the Excel app early, but if the instance is still running in Task Manager when the GUI is closed, the ReleaseComObject() call does not end the Excel instance.

asked on Stack Overflow Sep 21, 2015 by sigil

1 Answer


Your instance of Application only knows a memory address where the COM object is ready to answer function calls. So, it does not notice when you kill the process. Any posterior call to that object will raise the RPC_E_DISCONNECTED or RPC_SERVER_UNAVAILABLE as hResult. We try to call something simple from the application, like Ready() or Caption(). If it returns one of those codes, we know it is disconnected. Otherwise, it is safe to send messages --like Quit()

answered on Stack Overflow Sep 22, 2015 by Carlos E. Ferro

User contributions licensed under CC BY-SA 3.0