我使用NativeWindow在托管代码中继承Win32窗口。但是,我在我的代码或NativeWindow中遇到一个错误,当父关闭时会抛出异常。我正在使用的代码是:
public partial class ThisAddIn
{
private VisioWindow visioWindow;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
visioWindow = new VisioWindow();
visioWindow.AssignHandle(new IntPtr(this.Application.Window.WindowHandle32));
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
visioWindow.ReleaseHandle();
}
#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
public class VisioWindow : NativeWindow
{
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
}
}
}
退出主程序时,出现此错误:
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in System.Windows.Forms.dll
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in System.Windows.Forms.dll
This program has encountered an error
显示父母遇到错误。
是否有一种不同的方法来覆盖父WndProc而不是使用NativeWindow?或者这段代码中是否有错误可以解决?
感谢。
答案 0 :(得分:2)
我不清楚它为什么会崩溃。使用Debug + Exception,Thrown标志来查找ThreadAbort异常的来源。有一件事是绝对错误的,你应该在窗户被摧毁时拆下手柄。您可以通过观察WM_NCDESTROY消息来执行此操作:
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
if (m.Msg == 0x82) this.ReleaseHandle();
}
答案 1 :(得分:1)
Microsoft解决了这个问题:https://blogs.msdn.microsoft.com/anandgeorge/2010/04/10/usage-of-nativewindow-assignhandlereleasehandle-when-unmanaged-code-is-involved/
当我们调用NativeWindow.ReleaseHandle时,调用将替换 使用User32的winproc!DefWindowProc [this]将导致应用程序 大多数时候都会崩溃。
为什么这是解决此问题的首选方法的背景: https://blogs.msdn.microsoft.com/oldnewthing/20031111-00/?p=41883