Crash when closing a VSTO 2010 Word document from a user control in the task pane when another document is open

Answered Crash when closing a VSTO 2010 Word document from a user control in the task pane when another document is open

  • Wednesday, September 22, 2010 9:37 PM
     
      Has Code

    After upgrading my VSTO Word solution from .net 3.5 to .net 4, I am receiving the following crash when trying to close my application from the Actions Pane if I have opened another Word document since my VSTO solution started:

    "The application domain in which the thread was running has been unloaded."

    I can easily reproduce the crash using the code below.

    Code for the VSTO solution, ThisDocument.vb:

    Public Class ThisDocument
    
      Public WithEvents _hi As UserControl1
    
      Private Sub ThisDocument_Startup() Handles Me.Startup
        _hi = New UserControl1
        Me.ActionsPane.Controls.Add(_hi)
      End Sub
    
      Private Sub CloseCallback() Handles _hi.CloseWord
        Me.ActionsPane.Controls.Remove(_hi)
        CommandBars("Task Pane").Visible = False
        _hi = Nothing
        If Me.Application.Documents.Count = 1 Then
          Me.Application.Quit()
        Else
          Me.Close()
        End If
      End Sub
    
      Private Sub ThisDocument_Shutdown() Handles Me.Shutdown
    
      End Sub
    
    End Class
    
    

    The user control is a very simple control with one button that raises an event.

    Public Class UserControl1
    
      Public Event CloseWord()
    
      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        RaiseEvent CloseWord()
      End Sub
    
    End Class
    
    

    Here are some details to note:

    • I am running Office 2007, targetting .net 4 with the Visual Studio 2010 Tools for Office Runtime.  I have not tested this against Office 2010.
    • This error is occurring in both Windows XP and Windows 7.
    • I did not have this issue when using .net 3.5 with VSTOR 3.0 SP1.
    • If I open a document before my VSTO solution loads, it will gracefully close.  Having multiple documents open is not the issue.  This only occurs when I open a document after my VSTO document loads, leave that second document open, and then try to close the document from the actions pane.
    • If I change the code to just close word completely using Me.Close() instead of checking for other open documents, I still receive the exception.
    • If I close the VSTO document by using the red X in the top corner, the exception does not get raised.
    • The exception is still raised even if I do not unload the usercontrol from the Actions Pane in the CloseCallback function.

All Replies

  • Friday, September 24, 2010 9:44 PM
     
      Has Code

    As a stopgap, I've written in some code to close any new Word documents before the VSTO document is allowed to close.

    Public Class ThisDocument
    
      Public WithEvents _hi As UserControl1
    
      Private _docsAtStartup As New List(Of String)
    
      Private Sub ThisDocument_Startup() Handles Me.Startup
        CatalogDocsAtStartup()
        _hi = New UserControl1
        Me.ActionsPane.Controls.Add(_hi)
      End Sub
    
      Private Sub CatalogDocsAtStartup()
        For Each doc As Word.Document In Me.Application.Documents
          _docsAtStartup.Add(doc.Path)
        Next
      End Sub
    
      Private Sub CloseNewlyStartedDocs()
        For Each doc As Word.Document In Me.Application.Documents
          If Not _docsAtStartup.Contains(doc.Path) Then
            doc.Close(False)
          End If
        Next
      End Sub
    
      Private Sub CloseCallback() Handles _hi.CloseWord
    
        CloseNewlyStartedDocs()
    
        Me.ActionsPane.Controls.Remove(_hi)
        CommandBars("Task Pane").Visible = False
        _hi = Nothing
    
        If Me.Application.Documents.Count = 1 Then
          Me.Application.Quit()
        Else
          Me.Close()
        End If
      End Sub
    
      Private Sub ThisDocument_Shutdown() Handles Me.Shutdown
    
      End Sub
    
    End Class
    
    
  • Monday, September 27, 2010 10:22 PM
     
     Answered

    I ended up using a Microsoft support ticket for this incident.  Apparently, this is a known bug with Visual Studio 2010 Tools for Office.  This is the workaround that I was instructed to use:

     

    Imports System.Runtime.InteropServices

     

    Public Class UserControl1

        <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _

        Private Shared Function FindWindow( _

         ByVal lpClassName As String, _

         ByVal lpWindowName As String) As IntPtr

        End Function

     

        <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _

        Private Shared Function PostMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Boolean

        End Function

     

        Public Event CloseWord()

     

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

            'RaiseEvent CloseWord()

     

            Dim WM_CLOSE As Integer

            WM_CLOSE = 16

            Dim HWnd As IntPtr

            HWnd = FindWindow("OpusApp", Globals.ThisDocument.ActiveWindow.Caption + " - Microsoft Word")

            PostMessage(HWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero)

     

        End Sub

     

    End Class

     

    • Marked As Answer by Amy LiModerator Wednesday, September 29, 2010 2:51 AM
    •  
  • Wednesday, May 02, 2012 7:59 AM
     
      Has Code

    Thank you for finding this information.

    For those who want it in C#:

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
    
    private void ThisDocumentStartup(object sender, EventArgs e) {
        const int wmClose = 16;
        var hWnd = FindWindow(null, ActiveWindow.Caption + " - Microsoft Word");
        PostMessage(hWnd, wmClose, IntPtr.Zero, IntPtr.Zero);
    }
    edit: tabified code


    Kevin Warner


    • Edited by blueKevin Wednesday, May 02, 2012 8:01 AM tabified code
    •  
  • Tuesday, June 26, 2012 11:19 AM
     
     

    Hi

    I have tried to use the code proposed by Ralph in my Excel VSTO document level project - FindWindow always returns a null hWnd:

    var hWnd = FindWindow(null, this.Name);
    var hWnd = FindWindow(null, this.Name + " - Microsoft Excel");

    where this is the the Workbook instance.

    Any idea?

    Georg

  • Tuesday, June 26, 2012 12:08 PM
     
     
    you already have hwnd of window in excel API - use Application.Hwnd property.
  • Tuesday, June 26, 2012 2:31 PM
     
      Has Code

    Hi Damian

    Thank you. Using Application.Hwnd worked - Excel was closed.

    But: what I was actually trying to do is the equivalent of

    Globals.ThisWorkbook.Close(false, missing, missing)

    i.e. close my VSTO Workbook, without getting the annoying 'The application domain in which the thread was running has been unloaded.' message.

    Is there a way at all?

    Georg

  • Tuesday, June 26, 2012 2:52 PM
     
     
    no idea, have you tried using VSTO SP1?
  • Tuesday, June 26, 2012 4:50 PM
     
     

    I have got Visual Studio 2010 SP1 - that should include VSTO 2010 SP1, I assume.

    Georg

  • Tuesday, June 26, 2012 4:58 PM
     
     
    yes, but does this error happen on your dev box or some other machine? remember that you would need to install vstor 2010 sp1 on target machine.
  • Tuesday, June 26, 2012 6:01 PM
     
     

    it happens on my development machine.

    when you say vstor 2010 sp1 - are you referring to the Visual Studio 2010 Tools for Office Runtime? If yes, how do I verify whether it is SP1? (in Control Panel > Programs and Features, I have 'Microsoft Visual Studio Tools for Office Runtime (x86)')

    Georg

  • Tuesday, June 26, 2012 7:26 PM
     
     

    Additional Information:

    Earlier in this thread, I complained about the, quote, annoying error message, unquote. This is not precise enough. It is a real crash of the document. The document appears in the restored documents pane when Excel is next opened.

    So this is a real problem. Can anyone from Microsoft propose a way to solve this problem?

    Georg