【问题标题】:Excel is closing unexpectedly when closing C# WinForms App called in a DLL关闭在 DLL 中调用的 C# WinForms 应用程序时 Excel 意外关闭
【发布时间】:2016-10-13 18:30:22
【问题描述】:

我有一个 C# Winforms 应用程序。我已将项目的输出类型设置为“类库”并使其 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# 代码中的程序类如下所示:

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

当我启动宏时,WinForms 窗口打开并且程序运行良好。

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

我已经发现的是:

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

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

当我调用 base.Dispose()-Method 传递'false'时

base.Dispose(false);

当我关闭 WinForms-Window 时 Excel 不会意外关闭,但是当我想在之后关闭 Excel 时,这是不可能的。我得到了这个“鼠标等待符号”并且不能做任何事情,所以我必须在 TaskManager 中终止 Excel 进程。

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

所以我的问题是:有谁知道我如何关闭我的 WinForms-App,然后以“正常方式”关闭 Excel。

非常感谢!

【问题讨论】:

    标签: c# winforms vba dll interop


    【解决方案1】:

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

    “当对象的 UserControl 属性为 False 时,该对象会在对该对象的最后一个编程引用被释放时被释放。如果此属性为 False,Microsoft Excel 会在会话中的最后一个对象被释放时退出。” https://msdn.microsoft.com/library/office/ff841219.aspx

    【讨论】:

    • 不确定我是否理解正确。在调用我的 app.Main() 方法之前,我只需在我的 VBA 代码中设置 Application.UserControl = True 。得到相同的结果.. Excel 意外关闭...
    • 我现在无法测试,但我是说在你的 Main() 方法中设置,而不是在 vba 代码中。也许程序在运行时正在修改它,idk ...
    【解决方案2】:

    问题在于 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多