SolidWorks VBS
SolidWorks 支持通過?VBScript(.vbs)腳本?進行簡單的二次開發(如自動化建模、批量操作等),但嚴格來說這屬于?腳本編程,而非傳統的插件(Plug-in)開發(插件通常基于 C#、等編譯型語言)。以下是?VBS 腳本開發的核心要點?和示例:
一、開發環境準備
-
SolidWorks 對象模型
VBS 腳本通過調用 SolidWorks 的?COM 對象接口?控制軟件,需了解其核心對象關系:SldWorks
:SolidWorks 應用程序對象(入口)。ModelDoc2
:文檔對象(零件、裝配體、工程圖)。PartDoc
/AssemblyDoc
/DrawingDoc
:具體文檔類型對象。Feature
/Sketch
/Dimension
:特征、草圖、尺寸等對象。
-
引用 SolidWorks COM 庫
基礎腳本示例:創建零件并拉伸
' 連接或啟動 SolidWorks
Set swApp = CreateObject("SldWorks.Application")
swApp.Visible = True ' 顯示界面' 創建零件文檔
Set part = swApp.NewPart()
Set model = part.GetModelDoc2()' 創建草圖(前視基準面)
Set sketchPlane = model.GetPlane(3) ' 前視基準面的 ID 為 3
model.SetCurrentPlane(sketchPlane)
model.SendMsgToActiveView("Select")
model.SketchManager.InsertSketch True ' 激活草圖' 繪制矩形(草圖坐標:原點為中心)
Set sketchMgr = model.SketchManager
Set rect = sketchMgr.CreateLine2(-25, 0, 25, 0) ' 水平線
sketchMgr.CreateLine2(25, 0, 25, 25) ' 垂直線(右)
sketchMgr.CreateLine2(25, 25, -25, 25) ' 水平線(上)
sketchMgr.CreateLine2(-25, 25, -25, 0) ' 垂直線(左)
model.SketchManager.ConvertTo2DSketch ' 閉合草圖' 退出草圖并拉伸
model.FeatureManager.ExitSketch
Set extrudeFeat = model.FeatureManager.InsertExtrude2( _True, False, False, 0, 10, 0, 0, 0, 0, 0, 0, False) ' 拉伸高度 10mm
?
修改尺寸
- 遍歷草圖尺寸并修改數值
For Each dim In model.SketchManager.GetSketch.DimensionsIf dim.GetName = "D1@草圖1" Thendim.SetValue3 20, 2, 0 ' 修改尺寸為 20mmEnd If
Next
批量操作(如批量保存文件)
Dim files()
files = Array("文件1.sldprt", "文件2.sldprt") ' 文件名列表
For Each file In filesSet model = swApp.OpenDoc(file, 1, 0, "") ' 打開零件(1 表示零件類型)model.SaveAs "D:\備份\" & file, 0, 0 ' 另存為新路徑model.Close()
Next
插件開發
SolidWorks 的 C# 插件開發基于?SolidWorks API(COM 接口),通過 .NET 框架實現與軟件的深度集成(如自定義工具欄、自動建模、工程圖批量處理等)。以下是?核心開發流程?和示例:
一、開發環境搭建
-
安裝依賴
- 安裝?SolidWorks(需與開發目標版本一致)。
- 安裝?SolidWorks SDK(隨 SolidWorks 安裝包提供,勾選 “API 工具”)。
- 安裝?Visual Studio(推薦 2019/2022,需啟用 “.NET 桌面開發” 工作負載)。
-
創建項目
- 打開 Visual Studio,新建?類庫(.NET Framework)?項目,目標框架選擇?.NET Framework 4.8(SolidWorks 2020+ 支持)。
- 添加 SolidWorks API 引用:
- 在 “解決方案資源管理器” 中右鍵 “引用”,選擇 “添加引用”。
- 瀏覽至 SolidWorks 安裝目錄(如?
C:\Program Files\SolidWorks Corp\SolidWorks
),引用以下 DLL:SolidWorks.Interop.sldworks.dll
(核心接口)SolidWorks.Interop.swconst.dll
(常量定義)
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;public class MyAddIn : ISwAddIn
{private SldWorks swApp; // SolidWorks 應用程序對象private int addInID; // 插件 ID// 插件加載時調用public bool ConnectToSW(object ThisSW, int Cookie){swApp = (SldWorks)ThisSW;addInID = Cookie;// 注冊命令(如添加菜單/按鈕)RegisterCommand();return true;}// 插件卸載時調用public bool DisconnectFromSW(){// 注銷命令UnregisterCommand();swApp = null;return true;}// 注冊自定義命令(示例:添加菜單按鈕)private void RegisterCommand(){int cmdID = 1001; // 自定義命令 IDswApp.AddCommandItem2(addInID, cmdID, "MyCommand", "示例命令", "點擊執行操作", swconst.swCommandItemType_e.swCommandItemType_Button, "Resources\\icon.ico", "Resources\\icon_small.ico");swApp.SetCommandHandler(cmdID, true, ref this); // 關聯命令處理函數}// 注銷命令private void UnregisterCommand(){swApp.RemoveCommandItem(addInID, 1001, swconst.swCommandItemType_e.swCommandItemType_Button);}// 處理命令點擊事件(需實現 _ISwAddInCallback 接口)public void OnCommand(int CmdID){if (CmdID == 1001){// 執行自定義邏輯(如創建零件)CreatePart();}}
}
?
?創建零件并添加拉伸特征
private void CreatePart()
{// 創建零件文檔ModelDoc2 part = swApp.NewPart();part = (ModelDoc2)swApp.ActiveDoc;// 繪制草圖(前視基準面)part.SetCurrentPlane((Plane)part.GetPlane((int)swconst.swPlaneName_e.swPlaneFront));part.SketchManager.InsertSketch(true);SketchManager sketchMgr = part.SketchManager;// 繪制矩形(原點為中心)sketchMgr.CreateLine2(-25, 0, 25, 0); // 水平線sketchMgr.CreateLine2(25, 0, 25, 25); // 垂直線(右)sketchMgr.CreateLine2(25, 25, -25, 25); // 水平線(上)sketchMgr.CreateLine2(-25, 25, -25, 0); // 垂直線(左)part.SketchManager.ConvertTo2DSketch(); // 閉合草圖// 退出草圖并拉伸part.FeatureManager.ExitSketch();object[] args = { true, false, false, 0, 10.0, 0, 0, 0, 0, 0, 0, false };part.FeatureManager.InsertExtrude2(args, 0); // 拉伸高度 10mm
}
遍歷打開的文檔
private void ListOpenDocuments()
{int docCount = swApp.GetDocumentCount();for (int i = 1; i <= docCount; i++){ModelDoc2 doc = (ModelDoc2)swApp.GetDocument(i);MessageBox.Show($"文檔名稱:{doc.GetPathName()}\n類型:{doc.GetType()}");}
}
注冊插件(兩種方式)
- 手動注冊:
編譯生成 DLL 后,在 SolidWorks 中依次點擊?工具 > 插件 > 瀏覽,選擇生成的 DLL 文件并勾選啟用。 - 代碼自動注冊:
在項目屬性中設置 “生成后事件”,使用?regasm
?工具注冊(需管理員權限)
regasm "$(TargetPath)" /codebase /tlb
高級功能擴展
-
自定義用戶界面
- 添加工具欄按鈕、菜單或 PropertyManager 面板:
csharp
// 添加工具欄按鈕 swApp.AddCommandManagerTab2("MyTools", "我的工具", 0, "Resources\\tab_icon.ico"); swApp.AddCommandItemToTab("MyTools", cmdID, swconst.swCommandItemType_e.swCommandItemType_Button);
- 添加工具欄按鈕、菜單或 PropertyManager 面板:
-
事件監聽
- 訂閱 SolidWorks 事件(如文檔打開、保存):
csharp
SldWorksEvents_Event swEvents = (SldWorksEvents_Event)swApp; swEvents.FileOpen += OnFileOpen; // 注冊文檔打開事件private void OnFileOpen(string fileName) {MessageBox.Show($"打開文檔:{fileName}"); }
- 訂閱 SolidWorks 事件(如文檔打開、保存):
-
性能優化
- 使用?
ModelDoc2.SetUserPreferenceToggle
?關閉重建預覽:csharp
part.SetUserPreferenceToggle((int)swUserPreferenceToggleOptions_e.swToggleOptions_RebuildOnModify, false);
- 使用?
六、常見問題與解決方案
-
COM 接口異常
- 確保 SolidWorks 已啟動,或通過?
Marshal.ReleaseComObject
?釋放對象引用。 - 避免跨線程操作 COM 對象,使用?
STAThread
?特性標記主入口。
- 確保 SolidWorks 已啟動,或通過?
-
版本兼容性
- 不同 SolidWorks 版本的 API 可能存在差異,需通過?
swApp.GetVersion()
?判斷版本并適配。
- 不同 SolidWorks 版本的 API 可能存在差異,需通過?
-
依賴部署
- 發布插件時需確保目標計算機安裝了對應版本的 SolidWorks 和 .NET Framework,并注冊插件 DLL。
參考資源
- SolidWorks API 幫助文檔:安裝 SolidWorks 后,在 “開始菜單” 中搜索?SolidWorks API Help。
- 官方示例代碼:SolidWorks SDK 安裝目錄下的?
samples\api
?文件夾。
阿雪技術觀
元筋牢封固,后天化先天,未來之窗 生命對抗螺旋算法LAAM。自從中年后,很多了記憶減退,學習力減弱,直到耄耋之年。系統不在于新,而在于知道自己在哪里,然后做出正確選擇。
普通人想要創造出從沒見過的新東西,真不是件容易事。老記著過去的事兒吧,又會妨礙發揮;可要是完全不依靠過去的經驗,直接去學全新的東西,也難。所以說工具的關鍵,不在于創造本身,而是能把過去的經驗整合起來,幫助大家站在“前人肩膀”上突破,這樣人們就不用花大量時間去記以前的事兒,能更快實現從量變到質變的突破啦。
?The essence is firmly sealed, transforming acquired knowledge into innate wisdom, representing the window to the future. Life fights against the spiral algorithm LAAM. Since reaching middle age, many have experienced a decline in memory and learning ability, continuing to old age. The system does not rely on novelty, but on knowing where you are, and then making the right choices.For ordinary people, creating something completely new that has never been seen before is truly not an easy task. Holding onto past experiences can hinder performance; however, if one completely disregards past experiences and directly learns something entirely new, it is also challenging. Thus, the key to tools lies not in the creation itself, but in the ability to integrate past experiences, helping individuals to break through while standing on the 'shoulders of giants,' so that people do not have to spend a lot of time remembering past events, and can achieve breakthroughs more quickly from quantitative change to qualitative change.
?