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调试。

 点链接按钮

 链接成功。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
solidworks-flexnet-server.zip是Solidworks软件的FlexNet服务器安装包。FlexNet是一种软件许可管理工具,它用于管理Solidworks软件的许可证。当用户购买Solidworks软件后,他们需要将FlexNet服务器安装在自己的计算机上,以便可以通过网络分发和控制软件的许可证。 安装solidworks-flexnet-server.zip需要以下步骤: 1. 首先,下载solidworks-flexnet-server.zip文件,并保存到本地计算机的一个文件夹中。 2. 解压缩zip文件到目标文件夹。解压缩完成后,你将会看到一个包含安装所需文件的文件夹。 3. 双击运行解压缩后的文件夹中的安装程序。这将启动安装向导。 4. 按照安装向导的指导完成安装过程。你需要接受许可协议、选择安装位置以及为服务器设置密码等。 5. 完成安装后,你可以启动FlexNet服务器程序,并通过配置文件设置许可证参数,如许可证类型、数量和许可证的有效期等。 6. 在Solidworks客户端上,将FlexNet服务器的地址配置为该服务器所在的计算机的IP地址或主机名。 7. 运行Solidworks软件时,它将会通过网络连接到FlexNet服务器,获取并使用许可证。 总结来说,solidworks-flexnet-server.zip是Solidworks软件许可证管理工具的安装包,它提供了分发和控制Solidworks软件许可证的功能。通过安装FlexNet服务器并进行正确配置,用户可以顺利使用Solidworks软件,并管理他们的许可证。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值