【问题标题】:C# COM App in VBA Crashing ExcelVBA 中的 C# COM 应用程序崩溃 Excel
【发布时间】:2018-07-16 20:20:06
【问题描述】:

为什么在关闭表单时这段代码会导致excel崩溃(表单为空白):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SimpleTest
{

    [ComVisible(true)]
    public interface ISimpleTestApp
    {
        void Show();
    }

    [ClassInterface(ClassInterfaceType.None)]
    public class SimpleTestApp : ISimpleTestApp
    {
        [STAThread]
        public void Show()
        {
            Application.Run(new SimpleForm());
            MessageBox.Show("Done");
        }
    }
}

MessageBox.Show("Done") 永远不会被调用。

【问题讨论】:

  • 您是否尝试过捕获异常?
  • 这是一个类库项目(.dll),对吧?不要调用Application.Run,只需新建表单并显示即可。也就是说,将调试器附加到您的 EXCEL.EXE 进程,并 edit 您的问题带有适当的异常详细信息。就目前而言,你的猜测和我的一样好。
  • 表单也应该被处理掉。 using (var form = new SimpleForm()) { form.Show(); MessageBox.Show("Done"); }

标签: c# vba com


【解决方案1】:

此代码有效,谢谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SimpleTest
{

    [ComVisible(true)]
    public interface ISimpleTestApp
    {
        void Show();
    }

    [ClassInterface(ClassInterfaceType.None)]
    public class SimpleTestApp : ISimpleTestApp
    {
        SimpleForm f;

        [STAThread]
        public void Show()
        {
            f = new SimpleForm();
            f.Show();
            f.FormClosed += F_FormClosed;
            MessageBox.Show("Done");
        }

        private void F_FormClosed(object sender, FormClosedEventArgs e)
        {
            f.Dispose();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2016-12-12
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多