Today, a netizen asked me about how to use Exe to operate multiple Solidworks. In fact, I have seen the solution before. It is obtained through the process and id, rather than the usual (SldWorks) Marshal.GetActiveObject("SldWorks.Application.Application. 27");
So I came back to check some information at night and found a solution. I streamlined it and made a dll. You can try it.
''' <summary>
''' 创建一个新的Solidworks并返回实例
''' </summary>
''' <param name="version">指定版本号,-1表示默认.</param>
''' <param name="suppressDialogs">True 则禁用solidworks弹出消息.</param>
''' <param name="requireMainWindow">True 表示运行完显示到主窗口</param>
''' <param name="startProcessTimeout">返回Null 如果SolidWorks在指定时间内没有打开。</param>
''' <param name="createWindowTimeout">返回Null 如果SolidWorks主窗口在指定时间内没有显示.</param>
''' <returns></returns>
Public Shared Function RunSolidWorks(version As Integer,
visible As Boolean,
Optional suppressDialogs As Boolean = False,
Optional requireMainWindow As Boolean = True,
Optional startProcessTimeout As Integer = 30,
Optional createWindowTimeout As Integer = 15) As SldWorks
Dim executablePath As String = CTFileSystem.GetSolidWorksExecutablePath(version)
If File.Exists(executablePath) = False Then Return Nothing
Dim info As ProcessStartInfo = New ProcessStartInfo(executablePath)
If suppressDialogs Then info.Arguments = "/r"
Dim process As Process = Process.Start(info)
Dim app As SldWorks = Nothing
Dim t As DateTime = DateTime.Now
While app Is Nothing
Threading.Thread.Sleep(1000)
If Math.Abs(DateTime.Now.Subtract(t).Seconds) > startProcessTimeout Then Return Nothing
'If it were possible to get a GUID from a process ID then we could use GetActiveObject instead of this
app = GetComObjectFromProcessId(process.Id)
End While
t = DateTime.Now
While IsRunning(isMainWindowCreated:=True) = False
Threading.Thread.Sleep(1000)
If Math.Abs(DateTime.Now.Subtract(t).Seconds) > createWindowTimeout Then Return Nothing
End While
If visible = False Then
Dim frame As Frame = app.Frame()
If frame Is Nothing Then Return app
Dim handle As IntPtr = frame.GetHWndx64()
If ShowWindow(handle, 0) Then Return app
End If
Return app
End Function
I just ran the test and it is relatively simple to use. I created two new solidworks 2018 windows with code:
private SldWorks sldWorks2018_1 = null;
private SldWorks sldWorks2018_2 = null;
private void button1_Click(object sender, EventArgs e)
{
sldWorks2018_1 = PStandAlone.RunSolidWorks(26, true, false, false, 30, 15);
}
private void button2_Click(object sender, EventArgs e)
{
sldWorks2018_2 = PStandAlone.RunSolidWorks(26, true, false, false, 30, 15);
}
private void button3_Click(object sender, EventArgs e)
{
sldWorks2018_1.SendMsgToUser("From 2018 -1");
sldWorks2018_2.SendMsgToUser("From 2018 -2");
}
Source code https://gitee.com/painezeng/PSWStandalone (vb.net)