在Outlook VSTO加载项中,C#不允许您将事件处理程序挂接到Application.Quit。

吕克·维德

微软文档说(https://docs.microsoft.com/zh-cn/previous-versions/office/developer/office-2010/ee720183(v=office.14)#practice-2-detecting-when-outlook-is -关机

若要检测Outlook正在关闭,可以在Outlook对象模型中使用Application对象的Quit事件来接收有关进程正在关闭的通知。确保对事件做出快速响应,并尽快将控制权返回给Outlook。

但是似乎只能在VB.Net中完成,C#不允许我这样做。有一个称为Quit()的方法以及一个称为Quit的事件,当我尝试将事件处理程序连接到该事件时,C#编译器说您不能在方法组上使用+ =。

顺便说一句,我试过了:您不能用C#中的同名事件和方法创建任何东西。语言不允许。

下面的示例是Outlook插件的VSTO项目模板代码,仅添加了QuitHandler方法,并尝试将其挂接到Quit事件。

输入代码时,intellisense会同时显示Quit事件和Quit方法供您选择,但是选择该事件会导致代码无法编译。

有没有一种方法可以明确告诉编译器您打算使用的退出事件

namespace OutlookAddIn2
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Application.Quit += MyQuitHandler;
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            // Note: Outlook no longer raises this event. If you have code that 
            //    must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
        }

        void MyQuitHandler()
        {

        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}

编译器输出(您可能会忽略en-US警告,就我的记忆而言,在所有版本的Visual Studio中,AFAICT都是在同一台计算机上安装Office和Visual Studio引起的。)

1>------ Build started: Project: OutlookAddIn2, Configuration: Debug Any CPU ------
1>CSC : warning CS2038: The language name 'en-US' is invalid.
1>D:\Temp\OutlookAddIn2\ThisAddIn.cs(7,10,7,26): error CS1656: Cannot assign to 'Quit' because it is a 'method group'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

当我在VB.Net中尝试相同操作时,该问题不存在,这可以编译:

Public Class ThisAddIn

    Private Sub ThisAddIn_Startup() Handles Me.Startup
        AddHandler Application.Quit, AddressOf MyQuitHandler
    End Sub

    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown

    End Sub

    Private Sub MyQuitHandler()

    End Sub

End Class

这是将Vusual Studio 2017与Resharper 2017.3.1一起使用。

在这种特殊情况下,我不认为Resharper应当受到指责:当符号缓存失效时,我已经看到了类似的错误消息,但是从来没有导致代码无法编译。相反,尽管代码编辑器指出了错误,它仍然可以编译和运行代码。

[编辑]顺便说一句,它也不是这样,我认为它还是隐式的

Application.Quit += new ApplicationEvents_11_QuitEventHandler(MyQuitHandler);
马克·朱可夫斯基

在Outlook中重复出现“没有应用程序退出”事件?

答案(我测试并确认可以正常工作):

((Outlook.ApplicationEvents_11_Event)Application).Quit 
+= new Outlook.ApplicationEvents_11_QuitEventHandler(ThisAddIn_Quit);

void ThisAddIn_Quit()
{
   System.Windows.Forms.MessageBox.Show("bye bye problem, I found the solution!!");
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章