When Microsoft Access is shutting down, how can I catch the current properties of a CustomTaskPane before the controls are disposed..?

巧了我就是萌 提交于 2020-01-25 07:26:08

问题


I've created a VSTO addin for Microsoft Access by following the directions by Microsoft guru Andrew Whitechapel here, and it's working nicely. But the addin has a CustomTaskPane, and I'm having an issue with it when Access is closing.

If the CustomTaskPane is open when Access closes, the addin should save the properties of the CustomTaskPane controls. If code for this is placed in ThisAddIn_Shutdown(), I receive the following error:

System.ObjectDisposedException: Cannot access a disposed object.
  at Microsoft.Office.Tools.CustomTaskPane.get_Control()
  at MyAddin.ThisAddIn.ThisAddIn_Shutdown(Object sender, EventArgs e) in C:\...\ThisAddIn.vb:line nn

I'm not sure if this is the normal operation of CustomTaskPanes or Windows Forms controls, or if it's because VSTO isn't designed for Access. I'm wondering if it happens because Access doesn't have application-level events such as Access.Application."OnClose", as do the other VSTO-approved apps such as Excel & Word.

After some experimentation I found a workaround by using the HandleDestroyed event for the controls, which occurs before Dispose(), and thus the control properties are still available. This works:

Private Sub TextBox1_HandleDestroyed(ByVal sender As System.Object, ByVal e As System.EventArgs) _
            Handles TextBox1.HandleDestroyed
    MsgBox(TextBox1.Text)
End Sub

Is there a better way..? Workarounds make me nervous.


回答1:


In following the trail of events, I realized the answer to my own question. The focal point is the Dispose method in usercontrol.designer.vb. However, it is widely known designer-generated code shouldn't be directly modified, as it can and will be refreshed and over-written after any subsequent changes to the usercontrol in the designer.

Except...that rule doesn't completely apply to certain methods such as Dispose. See here. If the programmer subsequently moves such methods from usercontrol.designer.vb to usercontrol.vb, the designer will defer to them in usercontrol.vb and will not regenerate them in usercontrol.designer.vb.

And so, we've arrived at the answer: move the Dispose method to usercontrol.vb, remove the System.Diagnostics.DebuggerNonUserCode attribute, and then add the necessary code to save the control properties, as shown below:

Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        SaveUserControlProperties()    <--- additional code added here
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        MyBase.Dispose(disposing)
    End Try
End Sub


来源:https://stackoverflow.com/questions/59697174/when-microsoft-access-is-shutting-down-how-can-i-catch-the-current-properties-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!