C# SolidWorks 二次开发 API —Solidworks的多开操作与连接指定版本Solidworks
今天有网友问我关于如何用Exe操作多个Solidworks的问题,其实之前我看到过解决方案,是通过进程和id获取,而不是我们平时常用的 (SldWorks)Marshal.GetActiveObject(“SldWorks.Application.27”);
所以晚上回来查了些资料,发现了有了解决方案,我精简了一下,做了个dll.大家可以试试。
''' <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
我刚刚进行了测试,用起来比较简单。我用代码新建了两个solidworks 2018窗口:
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");
}
源码https://gitee.com/painezeng/PSWStandalone(vb.net)
posted @
2020-04-17 10:00
painezeng 阅读(
250) 评论(
0)
编辑
收藏
举报