tags:

views:

270

answers:

1

I am subclassing a Win32 window in managed code using NativeWindow. However, I'm encountering a bug in either my code or with NativeWindow that throws an exception when the parent is closed. The code I'm using is this:

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);

    }

}

}

On exit of the main program, I get this error:

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

And the "This program has encountered an error" shows up saying the parent encountered an error.

Is there a different way to override the parent's WndProc than using NativeWindow? Or is there a bug in this code that could be worked out?

Thanks.

+1  A: 

It isn't exactly clear to me why it would crash. Use Debug + Exception, Thrown flag to find out where the ThreadAbort exception is coming from. One thing is definitely wrong, you should detach the handle when the window is destroyed. You could do this by watching for the WM_NCDESTROY message:

protected override void WndProc(ref Message m) {
  base.WndProc(ref m);
  if (m.Msg == 0x82) this.ReleaseHandle();
}
Hans Passant
I tried doing just that. I am never getting WM_NCDESTROY from the parent. The last message I get is WM_PARENTNOTIFY. I had been releasing the handle in my shutdown code, I just forgot it here. I put the Thrown and User-Unhandled exceptions on in the Debugging->Exceptions menu, that's what you meant right? I feel like the exception is coming from the parent. I should note that this is the bare code of a larger program I have (but this is a standalone version), and this code is definitely causing the error. Without AssignHandle to the parent, I never get the error.
Max
If I catch WM_CLOSE and then release the handle there, I avoid the thread abort exception from windows forms.Thanks.
Max