Excel 关闭在 DLL 中调用的 C# WinForms 应用程序时意外关闭

Excel is closing unexpectedly when closing C# WinForms App called in a DLL

我有一个 C# Winforms 应用程序。我已将项目的输出类型设置为 'Class Library' 并使其 COM 可见,因此我可以在 Excel 中的 VBA 代码中引用它。因此我可以通过 Excel.

启动我的 WinForms-App

到目前为止一切正常。在我的 VBA 代码中,我这样调用应用程序(宏):

Dim app As MyWinFormsApp.Program
Set app = New MyWinFormsApp.Program
Dim result As Integer
result = app.Main()

我的 C# 代码中的程序 Class 如下所示:

public int Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
        return 0;
    }

当我启动我的宏时,WinForms Window 打开并且程序运行正常。

我的问题是:当我通过单击红色 X 关闭 WinForms Window 时,Excel 也意外关闭。

我已经发现的是:

在我的 C# 中 Class Form1.Designer.cs 我有这个 Dispose-Method:

protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

当我调用 base.Dispose()-方法传递 'false'

base.Dispose(false);
当我关闭 WinForms-Window 时,

Excel 并没有意外关闭,但是当我之后想关闭 Excel 时,这是不可能的。我得到这个 'Mouse-Wait-Symbol' 但无法执行任何操作,所以我必须在 TaskManager 中终止 Excel-Process。

(我也尝试过使用一个新的 WinForms 项目,它实际上并没有提供在我原来的项目中我做错了什么......我有完全相同的行为。)

所以我的问题是:有谁知道我如何关闭我的 WinForms-App 然后在 'normal way'. [=15] 中关闭 Excel =]

非常感谢!

尝试在关闭 winform 之前将 Application.UserControl 属性 更改为 true。

"When the UserControl property is False for an object, that object is released when the last programmatic reference to the object is released. If this property is False, Microsoft Excel quits when the last object in the session is released." https://msdn.microsoft.com/library/office/ff841219.aspx

问题是 Application.Run() 的使用。 如果您从 VBA 调用表单,您应该使用 frm.show().

然后它就会像魅力一样工作。 C# 中的示例:

        public void InitializeForm()
    {
        Form1 Form = new Form1();
        Form.Show();
    }

VBA中的示例:

Sub OpenForm()
Dim CallForm As New CallAndInitialize
CallForm.InitializeForm End Sub