我正在使用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就会出现,说明父进程遇到了错误。
与使用NativeWindow相比,有没有不同的方法来重写父级的WndProc?或者,这段代码中有没有可以解决的bug?
谢谢。
发布于 2009-07-18 20:48:02
我不太清楚为什么它会崩溃。使用调试+异常,抛出标志来找出ThreadAbort异常来自哪里。有一件事肯定是错的,当窗户被破坏时,你应该拆下手柄。您可以通过查看WM_NCDESTROY消息来完成此操作:
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
if (m.Msg == 0x82) this.ReleaseHandle();
}发布于 2016-07-02 15:03:01
当我们调用NativeWindow.ReleaseHandle时,调用会用User32替换winproc!DefWindowProcthis会导致应用程序大部分时间崩溃。
关于为什么这是解决这个问题的首选方法的背景:https://devblogs.microsoft.com/oldnewthing/20031111-00/?p=41883
https://stackoverflow.com/questions/1148200
复制相似问题