I am using the following code in Solidworks 2017 Visual Studio Tools for Applications. It's Microsoft Visual Studio 2005 Version 8.0.50727.42 running Microsoft Visual Basic 2005 and Microsoft .NET Framework Version 2.0.50727 SP2.
Public Sub Reference_GetCurrentPartorAssembly(ByRef CurrentFile As SolidWorks.Interop.sldworks.ModelDoc2)
CurrentFile = swApp.ActiveDoc
If IsNothing(CurrentFile) Then Throw New Exception("Could not get reference to current part or assembly.")
End Sub
Generally, the code works fine. However, sometimes there are extra instances of Solidworks running which are listed under the "background processes" list in Windows Task Manager. When that happens, my code throws the exception. To get my code to execute without the exception, I have to find the stray solidworks background process and force kill it using Task Manager.
(I have no idea why these background versions of Solidworks show up.)
I did not find Solidworks' documentation on ActiveDoc to be very helpful: http://help.solidworks.com/2017/english/api/sldworksapi/solidworks.interop.sldworks~solidworks.interop.sldworks.isldworks~activedoc.html?verRedirect=1
My question is: how can I get a reference to the current document without having to force-kill those background processes? I tried looking for other ways to get the reference to the active document but most code samples I have find all use ActiveDoc.