一.SolidWorks二次开发之 文档操作和设置

访问项目 Github仓库

查看在线文档

使用Nuget:

PM> Install-Package Du.SolidWorks -Version 0.1.1

本节源码

1.如何打开一个文档

SolidWorks Api 在SldWorks接口中为我们提供了很多OpenDoc方法来打开一个SolidWorks文件或者SolidWorks兼容的文件,如下


i文档打开方法

我使用的为2016版的帮助文档,文档中指示OpenDoc - OpenDoc4 已经是Obsolete状态,表示新版本中已经不在推荐使用,在Api演进过程中已经是过时Api.

使用 OpenDoc6打开文档

1.1打开文档

这里使用c#的扩展方法封装了一个静默打开文档的方法,这里隐藏了OpenDoc6的很多参数,只使用了一个路径字符串和一个用来控制文档是否可见的bool值.

        /// 
        /// 静默模式打开隐藏文件
        /// 
        /// 
        /// 文件路径
        /// 是否隐藏 默认隐藏
        /// 
        public static ModelDoc2 OpenInvisibleDocClient(this SldWorks app, string filePath, bool Hidden = true)
        {
            int Errors = -1, Warning = -1;
            var type = app.FileType(filePath);
            try
            {
                if (Hidden) app.DocumentVisible(false, (int)type);

                ModelDoc2 doc = app.OpenDoc6(filePath, type.SWToInt(), swOpenDocOptions_e.swOpenDocOptions_Silent.SWToInt(),
                    "", ref Errors, ref Warning) as ModelDoc2;

                if (doc == null)
                {
                    throw new Exception(string.Format("errors:{0},warings{1}",
                        Errors.CastObj().ToString(),
                        Warning.CastObj().ToString()));
                }

                return doc;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                app.DocumentVisible(true, (int)type);
            }
        }

下面根据文件路径判断SolidWorks文档类型的方法

        /// 
        /// 判断文件类型
        /// 
        /// 
        /// 文件全路径
        /// 
        public static swDocumentTypes_e FileType(this SldWorks app, string filePath)
        {
            string extension = Path.GetExtension(filePath).ToLower();
            swDocumentTypes_e type = swDocumentTypes_e.swDocPART;
            switch (extension)
            {
                case ".sldprt":
                    type = swDocumentTypes_e.swDocPART;
                    break;
                case ".sldasm":
                    type = swDocumentTypes_e.swDocASSEMBLY;
                    break;
                case ".slddrw":
                    type = swDocumentTypes_e.swDocDRAWING;
                    break;
                default:
                    throw new FileFormatException("不支持的文件类型:" + extension);
            }
            return type;
        }

1.2.只读打开

除了静默打开,我们有时候会在后台打开一个文件作为数据库使用,像草图轮廓库,特征数据库等.这时我们可以使用只读模式打开.下面的方法封装了OpenDoc7 来实现一个只读打开.

        /// 
        /// 以不可见模式打开文档  Open a document invisibly. It will not be shown to the user but you will be
        /// able to interact with it through the API as if it is loaded.
        /// 
        /// 
        /// 
        /// 是否对用户可见
        ///  SolidWorks 文件类型 ,默认为零件
        /// 
        public static ModelDoc2 OpenInvisibleReadOnly(this ISldWorks sldWorks, string toolFile, bool visible = false, swDocumentTypes_e type = swDocumentTypes_e.swDocPART)
        {
            try
            {
                if (!visible)
                    sldWorks.DocumentVisible(false, (int)type);
                var spec = (IDocumentSpecification)sldWorks.GetOpenDocSpec(toolFile);
                if (!visible)
                {
                    spec.Silent = true;
                    spec.ReadOnly = true;
                }
                var doc = sldWorks.OpenDoc7(spec);

                doc.Visible = visible;
                return doc;
            }
            finally
            {
                if (!visible)
                    sldWorks.DocumentVisible
                        (true,
                            (int)
                                type);

            }
        }

1.3.遍历打开的文档

SolidWorks提供了 GetDocuments 方法来获取所有打开的文档,其中包括在内存中打开并对用户不可见的文档,这立封装了一个方法,来遍历所有的文档并执行同一操作.

        /// 
        /// 对内存中所有文档进行操作
        /// 
        /// 
        /// 
        public static void UsingOpenDoc(this SldWorks swApp, Action action)
        {
            var docs = (swApp.GetDocuments() as Object[]).Cast();

            if (docs == null)
            {
                return;
            }

            foreach (var item in docs)
            {
                action?.Invoke(item);
            }
        }

1.4.判断文档是否已经打开

有时在打开前我们需要判断是否已经打开此文档,虽然对已经打开的文档再次打开SolidWorks也会返回到ModelDoc2对象,但有时判断一下还是很有必要.下面的方法便是对上面遍历所有文档的再次封装来实现判断此文档是否已经被打开.实现如下:

        /// 
        /// 判断此文档是否打开
        /// 
        /// 
        /// 
        /// 
        public static bool HasDocOpened(this SldWorks app, string DocFilePathName)
        {
            bool exist = false;
            app.UsingOpenDoc(d =>
            {
                if (d.GetPathName() == DocFilePathName)
                {
                    exist = true;
                }
            }
            );
            return exist;
        }

1.5.对当前打开的活动文档执行动作

对当前活动文档执行某些操作是相当普遍的做法,下面的方法使用了一个 Action类型的参数来对活动文档快速调用.适合一些对活动文档的快速操作.

        /// 
        /// 对活动文档进行操作
        /// 
        /// 
        /// 
        public static void UsingActiveDoc(this SldWorks swApp, Action action)
        {
            if (swApp.ActiveDoc != null)
            {
                action?.Invoke((IModelDoc2)swApp.ActiveDoc);
            }
        }

2.新建SolidWorks零件或者装配体

2.1.调用默认模板创建零件或者装配体

在对SolidWorks开发中,新建一个零件或者装配体是再经常不过的高频操作,下面的方法封装了一个创建文档的操作,并针对中文环境下SolidWork默认模板文件命名变换的情况做了判断处理.

        /// 
        /// 以默认设置的模板创建文档
        /// 
        /// 
        /// 
        /// 
        public static IModelDoc2 CreateDocument(this ISldWorks sldWorks, swDocumentTypes_e type)
        {
            string templatePath = string.Empty;
            switch (type)
            {
                case swDocumentTypes_e.swDocPART:
                    templatePath = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);
                    break;
                case swDocumentTypes_e.swDocASSEMBLY:
                    templatePath = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateAssembly);
                    break;
                case swDocumentTypes_e.swDocDRAWING:
                    templatePath = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateDrawing);
                    break;
                default:
                    break;
            }

            if (!File.Exists(templatePath))
            {
                templatePath =
                    Path.GetDirectoryName(templatePath) + "\\" +
                    Path.GetFileName(templatePath).
                    Replace("零件", "gb_part").
                    Replace("装配体", "gb_assembly").Replace("工程图", "gb_a1");
            }

            if (!File.Exists(templatePath))
            {
                throw new FileNotFoundException("无法找到SolidWorks文件--" + templatePath);
            }

            return sldWorks.CreateDocument(templatePath);
        }

2.2.通过模板新建文档

上面我们通过获取SolidWorks默认设置的模板来新建一个零件或者装配体,下面我们通过一个给定的模板路径来新建一个零件或者装配体。

        /// 
        /// 通过模板创建新零件或者新项目
        /// 
        /// 
        /// *.asmdot 或者 *.prtdot
        /// 
        public static ModelDoc2 NewPartOrAssembly(this SldWorks app, string TemFilePath)
        {
            return app.NewDocument(TemFilePath, (int)swDwgPaperSizes_e.swDwgPaperA4size, 100, 100) as ModelDoc2;
        }

3.修改SolidWorks设置

获取SolidWorks设置选项的基本方法在ISldWorks接口下,如下


获取SolidWorks设置选项

修改SolidWorks设置选项的方法也在ISldWorks接口下,大概与获取相对应,如下:
修改SolidWorks设置项

3.1 先获取设置项,执行完需要的代码后,将选项设置为默认状态

下面的代码演示了如何在某种状态下执行我们的业务代码,然后将设置选项还原到默认状态,以达到不随意改变用户设置的要求。

        /// 
        /// 设置一个选项后执行动作,执行完后设置回系统默认值
        /// 
        /// ISldwork interface
        /// 需要设置的枚举值
        /// 值
        /// 执行的动作
        public static void WithToggleState(this ISldWorks app, swUserPreferenceToggle_e toggleSetting, bool value, Action action)
        {
            try
            {
                bool fileLockState = app.GetUserPreferenceToggle(toggleSetting.SWToInt());
                app.SetUserPreferenceToggle(swUserPreferenceToggle_e.swLockRecentDocumentsList.SWToInt(), true);
                action?.Invoke();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                app.SetUserPreferenceToggle(toggleSetting.SWToInt(), value);
            }
        }

下一篇:

你可能感兴趣的:(一.SolidWorks二次开发之 文档操作和设置)