I wanted a way to get the latest version of SolidWorks installed (if SolidWorks wasn't already open) on a machine to automate with a Standalone. I thought this might be useful for anyone working on machines where the installer neglected to uninstall the previous versions of SolidWorks, but the latest version is preferred.
I do this by:
- getting the current year (System.DateTime.Now.Year) at the time of execution
- adding two years (for good measure, maybe only one is necessary)
- subtracting the first SW year (1992) to get that RevisionNumber
- iterating backwards until SolidWorks app is found, or REV# < 0 to end processing.
using System;
using SolidWorks.Interop.sldworks;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;//For MessageBox
///
/// Gets SolidWorks Session
///
/// True gets only the current session, False opens new session if session not already active.
/// "YYYY" for year, or "VV" for version.
/// /// True to end if null, False to return null if app not found
/// app if found, null if not.
public static SldWorks GetSolidWorks(bool CurrentSessionOnly = false, string version = "", bool EndIfNull = false)
{
int i = DateTime.Now.Year + 2 - 1992;
SldWorks app = null;
if (version != "")
{
int j = Convert.ToInt32(version);
if (version.Length == 4)
j = j - 1992;
try
{
app = (SldWorks)Marshal.GetActiveObject(\$"SldWorks.Application.{j.ToString()}");
}
catch (Exception) { }
if (app == null && CurrentSessionOnly == false)
{
try
{
app = (SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID(\$"SldWorks.Application.{j.ToString()}"));
}
catch (Exception) { }
}
if (app == null)
Debug.Print("Could not get that version of Solidworks. Latest installed version will be fetched.");
}
if (app == null)
{
try
{
app = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
}
catch (Exception)
{
if (CurrentSessionOnly == false)
{
do
{
try
{
app = (SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID(\$"SldWorks.Application.{i.ToString()}"));
}
catch (Exception) { }
--i;
if (i < 0)
break;
} while (app == null);
}
}
}
if (app == null)
{
MessageBox.Show("SolidWorks not found or\n" +
"system date may be incorrect.\n" +
"Program will terminate.",
"SolidWorks Not Found");
if (EndIfNull == true)
System.Environment.Exit(0);
}
else
app.Visible = true;
return app;
Feel free to post if you have a better solution or suggestions on this code.
SolidworksApi/macros