NativeWindow用于子类化的替代方法

时间:2009-07-18 18:22:06

标签: c# wpf winforms

我使用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?或者这段代码中是否有错误可以解决?

感谢。

2 个答案:

答案 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://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/09/99/38/21/Sample.zip

为什么这是解决此问题的首选方法的背景: https://blogs.msdn.microsoft.com/oldnewthing/20031111-00/?p=41883