c# - 用于子类化的 NativeWindow 的替代方案

标签 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

并且显示此程序遇到错误,表示父级遇到错误。

与使用 NativeWindow 相比,是否有其他方法可以覆盖父级的 WndProc?或者这段代码中是否存在可以解决的错误?

谢谢。

最佳答案

我不太清楚为什么它会崩溃。使用 Debug + Exception, Thrown flag 找出 ThreadAbort 异常来自何处。有一点肯定是错误的,当 window 被破坏时,你应该拆下 handle 。您可以通过观察 WM_NCDESTROY 消息来做到这一点:

protected override void WndProc(ref Message m) {
  base.WndProc(ref m);
  if (m.Msg == 0x82) this.ReleaseHandle();
}

关于c# - 用于子类化的 NativeWindow 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1148200/

相关文章:

c# - 在给定文化的字符串中查找不区分大小写的第一个差异

c# - 如何将具有多个组件的应用程序部署到 Azure?

c# - 使用 ItemsSource 时访问 MenuItem 中的子项,C#\WPF

wpf - 根据数据绑定(bind) ItemsSource 项中的值有条件地更改 WPF ComboBox 项的前景

c# - 如何修复 .NET Windows 应用程序在启动时崩溃并出现异常代码 : 0xE0434352?

c# - 在winforms中填充一个巨大的对象

c# - 如果 C# .NET 出现错误,如何让我的代码跳过某些内容

c# - 从设置中将文本 block 内容设置为字符串

.net - 是否可以使用 Katana 在 WinForms 应用程序中托管现有的 WebForms 应用程序?

c# - 在结构之间复制属性