检测Excel是否已退出并正确响应的正确方法? [英] Proper way to detect if Excel has been quit and respond appropriately?

查看:58
本文介绍了检测Excel是否已退出并正确响应的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows Forms应用程序,可以打开一个Excel实例.如果用户提前退出了该应用程序,则我想确保此Excel实例已退出.如果实例不是 null ,我尝试调用Excel实例的 Quit()方法,如下所示:

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();
            }
        }
    }

但是,如果我在任务管理器中退出Excel应用程序,然后关闭GUI,则会出现此错误:

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)

在即时"窗口中对(xlApp == null)的检查显示,即使没有运行Excel的实例, xlApp 也不为空.

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

所以我尝试删除 Quit()行并改用它:

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

Marshal.ReleaseComObject(form1.xlApp);

当用户提前退出Excel应用程序时,此操作可以很好地关闭而不会出现错误,但是如果在关闭GUI时实例仍在任务管理器中运行,则 ReleaseComObject()调用不会结束Excel实例.

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.

推荐答案

您的Application实例仅知道COM对象准备应答函数调用的内存地址.因此,它不会通知您何时终止进程.任何对该对象的后调用都会将RPC_E_DISCONNECTED或RPC_SERVER_UNAVAILABLE提升为hResult.我们尝试从应用程序中调用一些简单的东西,例如Ready()或Caption().如果它返回这些代码之一,则表明它已断开连接.否则,可以安全地发送消息,例如Quit()

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()

这篇关于检测Excel是否已退出并正确响应的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆