Solidworks学习笔记-链接Solidworks
本文用的是SolidWokrs2019 和 VS2019
1)创建窗口程序
2)添加引用
3)创建自己的功能类 并编写代码
Sld4File.cs
添加命名空间
using SolidWorks.Interop.sldworks; //接口对象
using SolidWorks.Interop.swconst; //枚举对象
编写功能函数:
这里注意:
CommandInProgress:通知 SOLIDWORKS 进程外应用程序将进行一系列 API 调用来提高进程外应用程序的性能。
EnableBackgroundProcessing:获取或设置是否开启后台处理。
using SolidWorks.Interop.sldworks; //接口对象
using SolidWorks.Interop.swconst; //枚举对象
using System;
//using SldExFunc.Model; //添加
namespace SldExFunc.Model
{
public static class Sld4File
{
// 判断进程是够存在,0无,1有
private static bool GetProc(string processName)
{
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();//得到所有打开的进程
try
{
foreach (System.Diagnostics.Process thisProcess in System.Diagnostics.Process.GetProcessesByName(processName))
{
return true;
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.ToString());
}
return false;
}
//连接solidworks
public static bool Conn2ProcById(Sld4Handler sld4Handler, string procId, bool isSendMsg = true)
{
if (GetProc("SLDWORKS"))
{
Type swType = Type.GetTypeFromProgID(procId); //通过指定程序标识,获得与其关联的类型
sld4Handler.SwApp = (SldWorks)Activator.CreateInstance(swType); //获取应用对象
sld4Handler.ModelDoc = (ModelDoc2)sld4Handler.SwApp.ActiveDoc; //获取当前激活文档
//向SW发送消息
if (sld4Handler.SwApp != null )
{
sld4Handler.SwApp.CommandInProgress = true;//
sld4Handler.SwApp.EnableBackgroundProcessing = true;//
if (isSendMsg == true)
sld4Handler.SwApp.SendMsgToUser("连接成功!");
}
return true;
}
else
{
if (isSendMsg == true) System.Windows.MessageBox.Show("当前无启动的Solidworks应用");
return false;
}
}
//获取当前打开文档的名称列表
public static System.Collections.Generic.List<string> GetModleName(Sld4Handler sld4Handler, bool isPath=true)
{
System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
EnumDocuments2 enumDocuments2 = sld4Handler.SwApp.EnumDocuments2();
ModelDoc2 modelDoc2 = null;
int nFetched = -1;
enumDocuments2.Reset();
do
{
enumDocuments2.Next(1, out modelDoc2, ref nFetched);
if (modelDoc2 != null)
{
string str0= modelDoc2.GetPathName();
if (isPath == true &&str0.Contains(@"\"))//名称存在路径的时候,截取获得最终所需的模型名
{
str0 = str0.Substring(str0.LastIndexOf(@"\") + 1, str0.Length - str0.LastIndexOf(@"\") - 1-(str0.Length - str0.LastIndexOf(".")));
}
list.Add( str0);
}
} while (modelDoc2 != null);
return list;
}
//②fileName :Document name or full path if not in current directory, including extension
//③fileType:
/*swDocASSEMBLY 2 装配体
//swDocDRAWING 3 工程图
//swDocIMPORTED_ASSEMBLY 7; Multi - CAD
//swDocIMPORTED_PART 6; Multi - CAD
//swDocLAYOUT 5
//swDocNONE 0
//swDocPART 1 零件
//swDocSDM 4 */
//④mode:
/*swOpenDocOptions_AutoMissingConfig 32 or 0x20 = Obsolete; do not use(丢失配置或参考,自动使用上次配置)
// The software automatically uses the last - used configuration of a model when it discovers missing configurations or component references as it silently opens drawings and assemblies.
//swOpenDocOptions_DontLoadHiddenComponents 256 or 0x100 = By default(打开时不加载隐藏项目)
// hidden components are loaded when you open an assembly document. Set swOpenDocOptions_DontLoadHiddenComponents to not load hidden components when opening an assembly document
//swOpenDocOptions_LoadExternalReferencesInMemory 512 or 0x200 = Open external references in memory only;(尽在内存中加载外部引用)
// this setting is valid only if swUserPreferenceIntegerValue_e.swLoadExternalReferences is not set to swLoadExternalReferences_e.swLoadExternalReferences_None swUserPreferenceToggle_e.swExtRefLoadRefDocsInMemory (System Options > External References > Load documents in memory only) is ignored when opening documents through the API because IDocumentSpecification::LoadExternalReferencesInMemory and ISldWorks::OpenDoc6(swOpenDocOptions_e.swOpenDocOptions_LoadExternalReferencesInMemory) have sole control over reference loading
//swOpenDocOptions_LoadLightweight 128 or 0x80 = Open assembly document as lightweight(轻量化打开)
// NOTE: The default for whether an assembly document is opened lightweight is based on a registry setting accessed via Tools, Options, Assemblies or with the user preference setting swAutoLoadPartsLightweight To override the default and specify a value with ISldWorks::OpenDoc6, set swOpenDocOptions_OverrideDefaultLoadLightweight. If set, then you can set swOpenDocOptions_LoadLightweight to open an assembly document as lightweight
//swOpenDocOptions_LoadModel 16 or 0x10 = Load Detached model upon opening document (drawings only)(打开文档时加载分离模型)
//swOpenDocOptions_OverrideDefaultLoadLightweight 64 or 0x40 = Override default setting whether to open an assembly document as lightweight(覆盖默认设置以轻量化方式打开装配体)
//swOpenDocOptions_RapidDraft 8 or 0x8 = Convert document to Detached format (drawings only)转化成分离格式
//swOpenDocOptions_ReadOnly 2 or 0x2 = Open document read only 只读
//swOpenDocOptions_Silent 1 or 0x1 = Open document silently 静默
//swOpenDocOptions_ViewOnly 4 or 0x4 = Open document in Large Design Review mode only (assemblies only) 大型审阅 */
public static ModelDoc2 OpenFile(Sld4Handler sld4Handler, string fileName, swDocumentTypes_e fileType, swOpenDocOptions_e mode, ref int error, ref int wraning, string cfg = "")
{
if (sld4Handler.SwApp == null) return null;
return sld4Handler.SwApp.OpenDoc6(fileName, (int)fileType, (int)mode, cfg, ref error, ref wraning);
}
//打开零件
public static PartDoc OpenPart(Sld4Handler sld4Handler, string fileName, ref int error, ref int wraning, string cfg = "", swOpenDocOptions_e mode = swOpenDocOptions_e.swOpenDocOptions_LoadModel)
{
object obj = OpenFile(sld4Handler, fileName, swDocumentTypes_e.swDocPART, mode, ref error, ref wraning, cfg);
if (obj is PartDoc) return obj as PartDoc;
return null;
}
//打开装配体
public static AssemblyDoc OpenAss(Sld4Handler sld4Handler, string fileName, ref int error, ref int wraning, string cfg = "", swOpenDocOptions_e mode = swOpenDocOptions_e.swOpenDocOptions_AutoMissingConfig)
{
object obj = OpenFile(sld4Handler, fileName, swDocumentTypes_e.swDocASSEMBLY, mode, ref error, ref wraning, cfg);
if (obj is AssemblyDoc) return obj as AssemblyDoc;
return null;
}
//打开工程图
public static DrawingDoc OpenDraw(Sld4Handler sld4Handler, string fileName, ref int error, ref int wraning, string cfg = "", swOpenDocOptions_e mode = swOpenDocOptions_e.swOpenDocOptions_LoadModel)
{
object obj = OpenFile(sld4Handler, fileName, swDocumentTypes_e.swDocDRAWING, mode, ref error, ref wraning, cfg);
if (obj is DrawingDoc) return obj as DrawingDoc;
return null;
}
//连接SldWorks
public static bool Connect2Sld(Sld4Handler sld4Handler, bool isSendMsg = true)
{
return (Conn2ProcById(sld4Handler, "SldWorks.Application", isSendMsg));
}
}
}
#region 第五章 应用程序对象
// dynamic ActivateDoc3(string Name, bool UseUserPreferences, int Option, ref int Errors); //激活目前打开的文档之一,并显示在用户面前
// void CloseDoc(string Name); //关闭指定文档
// void ExitApp(); //退出SW应用
// dynamic GetDocuments(); //得到所有当前SW进程中打开的文档对象
// dynamic NewDocument(string TemplateName, int PaperSize, double Width, double Height); //新建文档
// ModelDoc2 OpenDoc6(string FileName, int Type, int Options, string Configuration, ref int Errors, ref int Warnings); //打开指定文档
// int CopyDocument(string SourceDoc, string DestDoc, object FromChildren, object ToChildren, int Option); //带参考复制文档
// void SetUserPreferenceToggle(int UserPreferenceValue, bool OnFlag); //选项中的系统设置内容
// bool SetUserPreferenceStringValue(int UserPreference, string Value); //选项中的系统设置内容
// bool SetUserPreferenceDoubleValue(int UserPreferenceValue, double Value); //选项中的系统设置内容
// bool SetUserPreferenceIntegerValue(int UserPreferenceValue, int Value); //选项中的系统设置内容
// http://help.solidworks.com/2019/English/api/SWHelp_List.html?id=270c22dd49384528bdc75222bd58262d#Pg0
// http://help.solidworks.com/2019/English/api/swconst/SolidWorks.Interop.swconst~SolidWorks.Interop.swconst_namespace.html?id=1cdc927a2c1f44c5aabb877541a3a649#Pg0
#endregion
这里主要用到Connect2Sld、Conn2ProcById、GetProc、Conn2ProcById。
======================================================================
Sld4Handler.cs
主要存了些对象变量
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SolidWorks.Interop.sldworks; //接口对象
using SolidWorks.Interop.swconst; //枚举对象
namespace SldExFunc.Model
{
public class Sld4Handler
{
private SldWorks swApp;//应用实例
private ModelDoc2 modelDoc;//定义了一个文档
private PartDoc partDoc; //零件文档
private AssemblyDoc assemblyDoc; //装配体文档
private DrawingDoc drawingDoc; //工程图文档
private ModelDocExtension modelDocExtension; //通用文档扩展
private CustomPropertyManager cusPropMgr; //自定义属性管理器对象
private SelectionMgr selectionMgr;//选择管理器
private Feature feature;//特征
private SolidWorks.Interop.sldworks.Attribute attribute;//属性
private Face2 face;//面
private Parameter parameter;//参数
public ModelDoc2 ModelDoc { get => modelDoc; set => modelDoc = value; }
public PartDoc PartDoc { get => partDoc; set => partDoc = value; }
public AssemblyDoc AssemblyDoc { get => assemblyDoc; set => assemblyDoc = value; }
public DrawingDoc DrawingDoc { get => drawingDoc; set => drawingDoc = value; }
public ModelDocExtension ModelDocExtension { get => modelDocExtension; set => modelDocExtension = value; }
public CustomPropertyManager CusPropMgr { get => cusPropMgr; set => cusPropMgr = value; }
public SldWorks SwApp { get => swApp; set => swApp = value; }
public SelectionMgr SelectionMgr { get => selectionMgr; set => selectionMgr = value; }
public Feature Feature { get => feature; set => feature = value; }
public SolidWorks.Interop.sldworks.Attribute Attribute { get => attribute; set => attribute = value; }
public Parameter Parameter { get => parameter; set => parameter = value; }
}
}
4)编写按钮功能
private void SW_Conect(object sender, RoutedEventArgs e)
{
if (Sld4File.Connect2Sld(sld4Handler,true))
{
sld4Handler.SwApp.CommandInProgress = true;
};
}
窗口添加Sld4Handler 对象
public partial class MainWindow : Window
{
Sld4Handler sld4Handler = new Sld4Handler();
public MainWindow()
{
InitializeComponent();
}
}
5)测试
首先要打开SolidWorks。
打开VS调试。
点链接按钮
链接成功。