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

0

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
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 form1 = new Form1();
            Application.Run(form1);
            form1.logFile.close();
            if (form1.xlApp != null)
            {
                form1.xlApp.Quit();
            }
        }
    }

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:

Marshal.ReleaseComObject(form1.xlApp);

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.

c#
excel
com
asked on Stack Overflow Sep 21, 2015 by sigil

1 Answer

1

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