如何修复由于NativeWindow在Excel VSTO项目中的ThreadAbortException?

在一个针对Office 2007和2010的VSTO项目中,我在ThisAddIn_Shutdown完成后得到一个ThreadAbortException。 我相信这是由我的NativeWindow实现引起的,我在关机中清理它。 我正在使用NativeWindow,以便我的VSTO插件可以有HotKeys,我可以检测哪些键被按下。

这里有一个类似的问题,但我没有使用它的forms,所以我不能使用这个解决scheme。

在这个线程中,问题得到了更好的解释。

您必须在closures之前在主Excel窗口中释放您的子类。 原因是加载程序调用closures响应主Excel窗口closures。 因此,如果您在Excel的主窗口closures之前还没有调用ReleaseHandle,WM_CLOSE将首先被调度到NativeWindow的托pipeWndProc。 这将托pipe代码放在加载器closures代码下面的堆栈中。 所以加载器调用closures并卸载AppDomain,但是堆栈继续放松,并遇到托pipe代码。 由于AppDomain已被卸载,因此抛出了AppDomainUnloadedException,但由于没有可用的处理程序,因此Excel崩溃。

但是我再次不能使用这个解决scheme,因为我没有使用这个解决scheme。

所以据我可以告诉解决办法是在Excelclosures之前清理NativeWindow的东西。

我怎样才能做到这一点?

我发现/想到的唯一的事情就是解决这个Word问题。 这是发送WM_CLOSE消息。 我可以取消一个应用程序退出清理我的本地窗口,并亲自closuresExcel。

但是我不确定Excel(2007/2010)是否知道什么时候closures,这足以取消。

尝试这个:

 public partial class ThisAddIn { public MyNativeWindow MyNativeExcelWindow { get; private set; } private void ThisAddIn_Startup(object sender, System.EventArgs e) { var excelHwnd_IntPtr = new IntPtr(Globals.ThisAddIn.Application.Hwnd); MyNativeExcelWindow = new MyNativeWindow(); MyNativeExcelWindow.AssignHandle(excelHwnd_IntPtr); ... } ... } public class MyNativeWindow : NativeWindow { private const int WM_CLOSE = 16; [DllImport("user32.dll")] static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); protected override void WndProc(ref Message m) { if (m.Msg == WM_CLOSE) { // Release handle for this native window before closing app... ReleaseHandle(); // Then go on closing... PostMessage(m.HWnd, Convert.ToUInt32(m.Msg), m.WParam.ToInt32(), m.LParam.ToInt32()); } else { // HERE YOU CAN PROCESS OTHER MESSAGES... base.WndProc(ref m); } } }