I have a VSTO add-in for MS Project that opens forms where the data is related to the specific project file that was active when the form was open. It is possible to open one form related to one project file, while having another different form open that is related to a second open project file.
When I close a project file I would like to check each open form, and close it if the forms base project ID equals the project ID of the project file that is closing. How do I access the open forms collection of the vsto application (or do something equivalent)? The Application.OpenForms object doesn't appear to exist in the vsto world.
Use a Dictionary object to store an instance of the form along with the name of the file. Every time a form is created, add it to the dictionary and when the project is closed, search the dictionary to close the appropriate copy.
Friend ProjectForms As New Dictionary(Of String, MyForm)
Friend Sub ShowForm()
Dim f As New MyForm
Try
ProjectForms.Add(ProjApp.ActiveProject.Name, f)
Catch AlreadyInTheDictionary As Exception
' do nothing, it's already in the dictionary
End Try
f.Show()
End Sub
Put this in the module with the application events (typically ThisAddIn).
Private Sub Application_ProjectBeforeClose(pj As MSProject.Project, ByRef Cancel As Boolean) Handles Application.ProjectBeforeClose
ProjectForms(pj.Name).Close()
End Sub