Exemplo n.º 1
0
 internal TabCommandInfo(swDocumentTypes_e docType, int cmdId,
                         swCommandTabButtonTextDisplay_e textType)
 {
     DocType  = docType;
     CmdId    = cmdId;
     TextType = textType;
 }
Exemplo n.º 2
0
        protected IDisposable NewDocument(swDocumentTypes_e docType)
        {
            var useDefTemplates = m_SwApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAlwaysUseDefaultTemplates);

            try
            {
                m_SwApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAlwaysUseDefaultTemplates, true);

                var defTemplatePath = m_SwApp.GetDocumentTemplate(
                    (int)docType, "", (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 100, 100);

                if (string.IsNullOrEmpty(defTemplatePath))
                {
                    throw new Exception("Default template is not found");
                }

                var model = (IModelDoc2)m_SwApp.NewDocument(defTemplatePath, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 100, 100);

                if (model != null)
                {
                    var docWrapper = new DocumentWrapper(m_SwApp, model);
                    m_Disposables.Add(docWrapper);
                    return(docWrapper);
                }
                else
                {
                    throw new NullReferenceException($"Failed to create new document from '{defTemplatePath}'");
                }
            }
            finally
            {
                m_SwApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAlwaysUseDefaultTemplates, useDefTemplates);
            }
        }
        public static ModelDoc2 OpenDocument(string path, swDocumentTypes_e documentType, string configuration = "")
        {
            if (!File.Exists(path))
            {
                MessageObserver.Instance.SetMessage($"Error at open solid works document {path} file not exists. Maybe it is virtual document", MessageType.Error);
                throw new Exception($"Error at open solid works document {path} file not exists. Maybe it is virtual document");
            }
            int errors = 0, warnings = 0;
            int openDocOptions = (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly;

            if (documentType == swDocumentTypes_e.swDocASSEMBLY)
            {
                openDocOptions += (int)swOpenDocOptions_e.swOpenDocOptions_LoadModel;
            }

            var SolidWorksDocumentument = SldWoksAppExemplare.OpenDoc6(path, (int)documentType, openDocOptions, configuration, ref errors, ref warnings);

            if (errors != 0)
            {
                MessageObserver.Instance.SetMessage($"Error at open solid works document {path}; error code {errors }, description error { (swFileLoadError_e)errors }");
            }
            if (warnings != 0)
            {
                MessageObserver.Instance.SetMessage("Warning at open solid works document: code {" + warnings + "}, description warning {" + (swFileLoadWarning_e)errors + "}");
            }
            return(SolidWorksDocumentument);
        }
Exemplo n.º 4
0
        public static ModelDoc2 OpenDocument(string path, swDocumentTypes_e documentType, string configuration = "00")
        {
            int errors = 0, warnings = 0;

            int openDocOptions = (int)swOpenDocOptions_e.swOpenDocOptions_Silent;

            if (documentType == swDocumentTypes_e.swDocASSEMBLY)
            {
                openDocOptions += (int)swOpenDocOptions_e.swOpenDocOptions_LoadModel;
            }

            var SolidWorksDocumentument = SolidWorksAdapter.SldWoksAppExemplare.OpenDoc6(path, (int)documentType, openDocOptions, configuration, ref errors, ref warnings);



            if (errors != 0)
            {
                MessageObserver.Instance.SetMessage("Error at open solid works document: code {" + errors + "}, description error {" + (swFileLoadError_e)errors + "}");
                throw new Exception("Failed open document");
            }
            if (warnings != 0)
            {
                MessageObserver.Instance.SetMessage("Warning at open solid works document: code {" + warnings + "}, description warning {" + (swFileLoadWarning_e)errors + "}");
            }


            return(SolidWorksDocumentument);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Run this function after this.Document is populated. It fills two ref vars with swDocumentTypes_e.
        /// </summary>
        /// <param name="d">The document type.</param>
        /// <param name="od">The top-level document type.</param>
        private void GetTypes(ref swDocumentTypes_e d, ref swDocumentTypes_e od)
        {
            swDocumentTypes_e docT     = (swDocumentTypes_e)Document.GetType();
            ModelDoc2         overDoc  = (ModelDoc2)_swApp.ActiveDoc;
            swDocumentTypes_e overDocT = (swDocumentTypes_e)overDoc.GetType();

            if ((docT != swDocumentTypes_e.swDocDRAWING && swSelMgr != null) && swSelMgr.GetSelectedObjectCount2(-1) > 0)
            {
                Component2 comp = (Component2)swSelMgr.GetSelectedObjectsComponent4(1, -1);
                if (comp != null)
                {
                    ModelDoc2 cmd = (ModelDoc2)comp.GetModelDoc2();
                    docT = (swDocumentTypes_e)cmd.GetType();
                    prop.GetPropertyData(comp);
                    comp = null;
                }
                else
                {
                    prop.GetPropertyData(Document);
                }
            }
            else
            {
                swSelMgr = null;
                prop.GetPropertyData(Document);
            }
            d  = docT;
            od = overDocT;
        }
        public SwModelWrapper(SwApiWrapper swApi, SldWorks swApp, swDocumentTypes_e swDocType, ModelDoc2 swMainModel, string strConfigName)
        {
            this.swApi       = swApi;
            this.swApp       = swApp;
            this.swMainModel = swMainModel;

            swModelDocExt = (ModelDocExtension)swMainModel.Extension;

            if (swDocType == swDocumentTypes_e.swDocASSEMBLY)
            {
                swMainAssembly = (AssemblyDoc)swMainModel;
            }

            if (strConfigName != null)
            {
                this.swMainConfig = (Configuration)swMainModel.GetConfigurationByName(strConfigName);
            }
            else
            {
                this.swMainConfig = (Configuration)swMainModel.GetActiveConfiguration();
            }
            strConfigName = this.swMainConfig.Name;


            // Write model info to shared variables
            string[] configsArray = swMainModel.GetConfigurationNames();
            this.configNames.AddRange(configsArray);
            this.configNames.Sort();
            this.pathName          = swMainModel.GetPathName();
            this.modelName         = swMainModel.GetTitle();
            this.currentConfigName = strConfigName;
        }
Exemplo n.º 7
0
 private void DocTypeValidate(swDocumentTypes_e docType)
 {
     if (SwModel.GetType() != (int)docType)
     {
         throw new SolidWorksInappropriateDocumentTypeException("Открытый документ должен иметь другой тип");
     }
 }
        /// <summary>
        /// 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.
        /// </summary>
        /// <param name="sldWorks"></param>
        /// <param name="toolFile"></param>
        /// <returns></returns>
        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 = SwAddinBase.Active.SwApp.OpenDoc7(spec);

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

            }
        }
Exemplo n.º 9
0
 /// <summary>
 /// Class constructor
 /// </summary>
 /// <param name="swModel">Модель документа</param>
 public SwModelManager(ModelDoc2 swModel)
 {
     if (!(swModel is null))
     {
         _swModel = swModel;
         DocType  = (swDocumentTypes_e)swModel.GetType();
         Debug.Print("SwModelManager: SwModel initialised");
     }
Exemplo n.º 10
0
 public static void GetSolidObject()
 {
     swApp             = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
     swModel           = swApp.ActiveDoc;
     docType           = (swDocumentTypes_e)swModel.GetType();
     configName        = swModel.GetActiveConfiguration().Name;//при первом вызове присваеваеться активная конфигурация
     Class.configNames = Class.GetAllConfigurations(out lockForConf);
 }
        public void FileTypeTest(swDocumentTypes_e type)
        {
            var doc = _unitSolidWorks.SwApp.CreateDocument(false, type);

            Assert.NotNull(doc);
            doc.SaveAs(SWPath.CreateATemFilePath(type));
            Assert.Equal((int)_unitSolidWorks.SwApp.FileType(doc.GetPathName()), (int)type);

            _unitSolidWorks.SwApp.CloseAllDocuments(true);
        }
Exemplo n.º 12
0
 public SolidWorksClient(swDocumentTypes_e docType)
 {
     SetSwApp();
     ActiveDocValidate();
     SwModel         = (ModelDoc2)SwApp.ActiveDoc;
     SwSketchManager = SwModel.SketchManager;
     SwSelMgr        = (SelectionMgr)SwModel.SelectionManager;
     SwFM            = SwModel.FeatureManager;
     DocTypeValidate(docType);
 }
Exemplo n.º 13
0
 public static void GetPropsFromModelFromDRW()
 {
     // подтягиваем свойства из модельки в чертеж
     swModel = swView.ReferencedDocument;
     docType = (swDocumentTypes_e)swModel.GetType();
     EditProp.configuracione = swView.ReferencedConfiguration;
     EditProp.FixPropertys();
     EditProp.GetProperties(EditProp.configuracione);
     swModel = swApp.ActiveDoc; // дальше опять работаем с чертежом
     EditProp.configuracione = "";
     docType = (swDocumentTypes_e)swModel.GetType();
 }
Exemplo n.º 14
0
        public SWglTFModel ConvertToglTFModel(ModelDoc2 swModel, out ErrorType errors)
        {
            SWglTFModel model = null;

            errors = ErrorType.DoNotKnow;
            ProgressStatus_event(0.01, "开始读取", ErrorType.NoErros);
            swDocumentTypes_e ModelType = (swDocumentTypes_e)swModel.GetType();

            switch (ModelType)
            {
            case swDocumentTypes_e.swDocNONE:
                errors = ErrorType.NoPartOrAssemblyDocument;
                return(null);

            case swDocumentTypes_e.swDocPART:
                ProgressStatus_event(0.02, "读取零件信息", ErrorType.NoErros);
                model = ConvertPartToglTF(swModel);
                ProgressStatus_event(0.5, "读取零件信息完成", ErrorType.NoErros);
                break;

            case swDocumentTypes_e.swDocASSEMBLY:
                ProgressStatus_event(0.02, "读取装配体信息", ErrorType.NoErros);
                model = ConvertAssemblyToglTF(swModel);
                ProgressStatus_event(0.5, "读取装配体信息完成", ErrorType.NoErros);
                break;

            case swDocumentTypes_e.swDocDRAWING:
                errors = ErrorType.NoPartOrAssemblyDocument;
                return(null);

            case swDocumentTypes_e.swDocSDM:
                errors = ErrorType.NoPartOrAssemblyDocument;
                return(null);

            case swDocumentTypes_e.swDocLAYOUT:
                errors = ErrorType.NoPartOrAssemblyDocument;
                return(null);

            case swDocumentTypes_e.swDocIMPORTED_PART:
                break;

            case swDocumentTypes_e.swDocIMPORTED_ASSEMBLY:
                break;
            }
            if (model == null)
            {
                errors = ErrorType.DoNotKnow;
            }
            return(model);
        }
Exemplo n.º 15
0
        //public static ModelDoc2 OpenDocument(string path, swDocumentTypes_e documentType, string configuration = "")
        //{
        //    if (!File.Exists(path))
        //    {
        //        MessageObserver.Instance.SetMessage($"Error at open solid works document {path} file not exists. Maybe it is virtual document", MessageType.Error);
        //        throw new Exception($"Error at open solid works document {path} file not exists. Maybe it is virtual document" );
        //    }
        //    int errors = 0, warnings = 0;
        //    int openDocOptions = (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly;
        //    if (documentType == swDocumentTypes_e.swDocASSEMBLY) {  openDocOptions += (int)swOpenDocOptions_e.swOpenDocOptions_LoadModel; }

        //    var SolidWorksDocumentument = SldWoksAppExemplare.OpenDoc6(path, (int)documentType, openDocOptions, configuration, ref errors, ref warnings);

        //    if (errors != 0)
        //    {
        //        MessageObserver.Instance.SetMessage($"Error at open solid works document {path}; error code {errors }, description error { (swFileLoadError_e)errors }" ) ;
        //    }
        //    if (warnings != 0)
        //    {
        //        MessageObserver.Instance.SetMessage("Warning at open solid works document: code {" + warnings + "}, description warning {" + (swFileLoadWarning_e)errors + "}");
        //    }
        //    return SolidWorksDocumentument;
        //}

        public static ModelDoc2 OpenDocument(string path, swDocumentTypes_e documentType, string configuration = "")
        {
            //if (!File.Exists(path))
            //{
            //    MessageObserver.Instance.SetMessage($"Error at open solid works document {path} file not exists. Maybe it is virtual document", MessageType.Error);
            //    throw new System.Exception($"Error at open solid works document {path} file not exists. Maybe it is virtual document");
            //}

            DocumentSpecification swDocSpecification;

            swDocSpecification                         = SolidWorksAdapter.SldWoksAppExemplare.GetOpenDocSpec(path);
            swDocSpecification.ReadOnly                = false;
            swDocSpecification.DocumentType            = (int)documentType;
            swDocSpecification.UseLightWeightDefault   = false;
            swDocSpecification.LightWeight             = false;
            swDocSpecification.Silent                  = true;
            swDocSpecification.IgnoreHiddenComponents  = false;
            swDocSpecification.ViewOnly                = false;
            swDocSpecification.InteractiveAdvancedOpen = false;
            swDocSpecification.ConfigurationName       = configuration;

            ModelDoc2 SolidWorksDocumentument = null;

            if (swDocSpecification != null)
            {
                SolidWorksDocumentument = SldWoksAppExemplare.OpenDoc7(swDocSpecification);
                if (SolidWorksDocumentument == null)
                {
                    MessageBox.Show("Failed to open document " + path + System.Environment.NewLine + "Error : " + (swFileLoadError_e)swDocSpecification.Error + System.Environment.NewLine +
                                    " Warning: " + (swFileLoadWarning_e)swDocSpecification.Warning);
                }
                else
                {
                    if (documentType == swDocumentTypes_e.swDocASSEMBLY)
                    {
                        int resolved = ((AssemblyDoc)SolidWorksDocumentument).ResolveAllLightWeightComponents(false);
                        MessageBox.Show("Resolve document with result: " + (swComponentResolveStatus_e)resolved);
                    }
                }
            }
            else
            {
                MessageBox.Show("Failed to get specification on " + path + System.Environment.NewLine + "Error : " + (swFileLoadError_e)swDocSpecification.Error + System.Environment.NewLine +
                                " Warning: " + (swFileLoadWarning_e)swDocSpecification.Warning);
            }

            return(SolidWorksDocumentument);
        }
Exemplo n.º 16
0
        private ModelDoc2 OpenSWDoc(string _FilePath)
        {
            try
            {
                this.swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            }
            catch
            {
                this.swApp = new SldWorks();
            }
            this.FileType = JswFunc.GetswFileType(_FilePath);
            int longstatus   = 0;
            int longwarnings = 0;

            return((ModelDoc2)this.swApp.OpenDoc6(_FilePath, (int)this.FileType, 0, "", ref longstatus, ref longwarnings)); //打开SW文件
        }
Exemplo n.º 17
0
        private bool TryClearTab(string tabName, swDocumentTypes_e docType, ref CommandTab cmdTab)
        {
            var cmdTabBoxes = (object[])cmdTab.CommandTabBoxes();

            if (cmdTabBoxes?.Any() == true)
            {
                foreach (CommandTabBox cmdTabBox in cmdTabBoxes)
                {
                    cmdTab.RemoveCommandTabBox(cmdTabBox);
                }

                if (cmdTab.GetCommandTabBoxCount() > 0)
                {
                    m_Logger.Log($"Failed to clear command tab boxes in '{tabName}' in {docType}", LoggerMessageSeverity_e.Debug);

                    var removeTabRes = CmdMgr.RemoveCommandTab(cmdTab);

                    if (!removeTabRes) //NOTE: sometimes API returns false despite the tab been removed correctly
                    {
                        removeTabRes = CmdMgr.GetCommandTab((int)docType, tabName) == null;
                    }

                    if (removeTabRes)
                    {
                        cmdTab = CmdMgr.AddCommandTab((int)docType, tabName);
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                return(true);
            }
        }
Exemplo n.º 18
0
        //private Boolean shouldCheck = true;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="sw">Requires a <see cref="SolidWorks.Interop.sldworks.SldWorks"/> type.</param>
        /// <param name="ps">Requires a <see cref="ArchivePDF.csproj.PathSet"/></param>
        public PDFArchiver(ref SldWorks sw, ArchivePDF.csproj.PathSet ps)
        {
            swApp    = sw;
            APathSet = ps;
            swModel  = (ModelDoc2)swApp.ActiveDoc;
            ModelDocExtension ex  = (ModelDocExtension)swModel.Extension;
            string            lvl = GetRev(ex);

            if (DocCheck())
            {
                if (swModel.GetType() != (int)swDocumentTypes_e.swDocDRAWING)
                {
                    throw new ExportPDFException("You must have a Drawing Document open.");
                }
                swDraw  = (DrawingDoc)swModel;
                swFrame = (Frame)swApp.Frame();

                swView      = GetFirstView(swApp);
                metal       = IsMetal(swView);
                sourcePath  = swView.GetReferencedModelName().ToUpper().Trim();
                drawingPath = swModel.GetPathName().ToUpper().Trim();

                if (sourcePath.Contains("SLDASM"))
                {
                    modelType = swDocumentTypes_e.swDocASSEMBLY;
                }
                else if (sourcePath.Contains("SLDPRT"))
                {
                    modelType = swDocumentTypes_e.swDocPART;
                }
                else
                {
                    modelType = swDocumentTypes_e.swDocNONE;
                }
            }
            else
            {
                MustSaveException e = new MustSaveException("The drawing has to be saved.");
                throw e;
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Написать список параметров сборки или детали
        /// </summary>
        /// <param name="swModelMan"></param>
        public static void ShowProp(SwModelManager swModelMan)
        {
            bool      ret     = false;
            const int offset  = 23;
            int       lineNum = 6;

            Console.CursorTop = lineNum;
            swDocumentTypes_e doctype = swModelMan.DocType;

            if (doctype == swDocumentTypes_e.swDocPART || doctype == swDocumentTypes_e.swDocASSEMBLY)
            {
                string NameProp    = swModelMan.PrpMan.Title;
                string parnNum     = swModelMan.PrpMan.GetParam("Обозначение");
                string configName  = swModelMan.PrpMan.GetActiveConf;
                bool   isDrawExist = SwFileManager.isDrawExcist(swModelMan.FilePath);
                bool   isSheet     = swModelMan.PrpMan.isSheet;

                string DrawIsFound  = isDrawExist ? "Найден" : "Не найден";
                string isSheetMetal = isSheet ? $"Листовая - {swModelMan.PrpMan.GetSheetThickness}мм" : "Не листовая";

                //Clear console below
                for (int i = lineNum; i < lineNum + 5; ++i)
                {
                    StringManager.ClearLine(i);
                }

                Console.CursorLeft = 0;
                Console.CursorTop  = lineNum;

                Console.WriteLine($"{"Обозначение: ",offset} {parnNum}");
                Console.WriteLine($"{"Наименование: ",offset} {NameProp}");
                Console.WriteLine($"{"Активная конфигурация: ",offset} {configName}");
                Console.WriteLine($"{"Одноимённый чертёж: ",offset} {DrawIsFound}");
                Console.WriteLine($"{"Тип детали: ",offset} {isSheetMetal}");
            }
            else
            {
                Console.WriteLine($"{"Имя чертежа: ",offset} {swModelMan.swModel.GetTitle()}");
            }
        }
        /// <summary>
        /// 以默认设置的模板创建文档
        /// </summary>
        /// <param name="sldWorks"><see cref="ISldWorks"/></param>
        /// <param name="type"><see cref="swDocumentTypes_e"/></param>
        /// <returns></returns>
        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));
        }
Exemplo n.º 21
0
        /// <summary>
        /// 生成一个随机的临时SolidWorks路径
        /// *.sldpart *.sldasm *.slddrw
        /// </summary>
        /// <param name="docType"></param>
        /// <returns></returns>
        public static string CreateATemFilePath(swDocumentTypes_e docType)
        {
            string FilePath = ExtensionDllPath;

            switch (docType)
            {
            case swDocumentTypes_e.swDocPART:
                FilePath = FilePath + "\\" + Guid.NewGuid().ToString() + SWFile.Part;
                break;

            case swDocumentTypes_e.swDocASSEMBLY:
                FilePath = FilePath + "\\" + Guid.NewGuid().ToString() + SWFile.Assembly;
                break;

            case swDocumentTypes_e.swDocDRAWING:
                FilePath = FilePath + "\\" + Guid.NewGuid().ToString() + SWFile.Drawing;
                break;

            default:
                throw new FileFormatException("不支持的文件类型:" + docType.ToString());
            }
            return(FilePath);
        }
Exemplo n.º 22
0
            /// <summary>
            /// Название типа детали
            /// </summary>
            /// <param name="docType"></param>
            /// <returns></returns>
            public static string DocTypeName(swDocumentTypes_e docType)
            {
                string typeMessage;

                switch (docType)
                {
                case swDocumentTypes_e.swDocASSEMBLY:
                    typeMessage = "Сборка";
                    break;

                case swDocumentTypes_e.swDocDRAWING:
                    typeMessage = "Чертёж";
                    break;

                case swDocumentTypes_e.swDocPART:
                    typeMessage = "Деталь";
                    break;

                default:
                    typeMessage = "Что то непонятное";
                    break;
                }
                return(typeMessage);
            }
Exemplo n.º 23
0
        public static object GetTemFileType(string templatePath)
        {
            string            extension = Path.GetExtension(templatePath).ToLower();
            swDocumentTypes_e type      = swDocumentTypes_e.swDocPART;

            switch (extension)
            {
            case ".prtdot":
                type = swDocumentTypes_e.swDocPART;
                break;

            case ".asmdot":
                type = swDocumentTypes_e.swDocASSEMBLY;
                break;

            case ".drwdot":
                type = swDocumentTypes_e.swDocDRAWING;
                break;

            default:
                throw new FileFormatException("不支持的文件类型:" + extension);
            }
            return(type);
        }
Exemplo n.º 24
0
        public static ModelDoc2 CreateHiddenDocument
            (this ISldWorks sldWorks, bool hidden = true, swDocumentTypes_e type = swDocumentTypes_e.swDocPART)
        {
            try
            {
                if (hidden)
                {
                    sldWorks.DocumentVisible(false, (int)type);
                }

                var partTemplateName = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);
                var doc = (ModelDoc2)sldWorks.NewDocument(partTemplateName, (int)swDwgPaperSizes_e.swDwgPaperA4size, 1, 1);
                doc.Visible = false;

                /*
                 * ModelView myModelView = null;
                 * myModelView = ((ModelView)(doc.ActiveView));
                 * myModelView.FrameLeft = 0;
                 * myModelView.FrameTop = 0;
                 * myModelView = ((ModelView)(doc.ActiveView));
                 *
                 * myModelView.FrameState = ((int)(swWindowState_e.swWindowMinimized));
                 */
                return(doc);
            }
            finally
            {
                if (hidden)
                {
                    sldWorks.DocumentVisible
                        (true,
                        (int)
                        type);
                }
            }
        }
        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 Exception("不支持的文件类型:" + extension);
            }
            return(type);
        }
Exemplo n.º 26
0
        /// <summary>
        /// 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.
        /// </summary>
        /// <param name="sldWorks"></param>
        /// <param name="toolFile"></param>
        /// <returns></returns>
        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 = SwAddinBase.Active.SwApp.OpenDoc7(spec);

                doc.Visible = visible;
                return(doc);
            }
            finally
            {
                if (!visible)
                {
                    sldWorks.DocumentVisible
                        (true,
                        (int)
                        type);
                }
            }
        }
Exemplo n.º 27
0
        public static List <Comp> GetColl(AssemblyDoc swAssy, SldWorks swApp)
        {
            Comp        component;
            List <Comp> coll;

            object[]              comps;
            Component2            comp;
            ModelDoc2             compDoc, swModel;
            CustomPropertyManager prpMgr;
            ModelDocExtension     swModelDocExt;
            swDocumentTypes_e     docType = swDocumentTypes_e.swDocPART;
            ConfigurationManager  confManager;
            string configuration;

            double[] aTrans;
            string   path;

            coll = new List <Comp>();

            swAssy.ResolveAllLightWeightComponents(false);

            comps = (object[])swAssy.GetComponents(true);

            for (int i = 0; i < comps.Length; i++)
            {
                component     = new Comp();
                swModel       = (ModelDoc2)swAssy;
                swModelDocExt = swModel.Extension;


                confManager   = (ConfigurationManager)swModel.ConfigurationManager;
                configuration = confManager.ActiveConfiguration.Name;
                prpMgr        = swModelDocExt.get_CustomPropertyManager(configuration);
                prpMgr.Get4("Обозначение", true, out string valOut, out _);
                component.used = valOut;

                comp = (Component2)comps[i];
                path = comp.GetPathName();
                if ((comp.GetSuppression() != (int)swComponentSuppressionState_e.swComponentSuppressed) & (comps[i] != null))
                {
                    aTrans = (double[])comp.Transform2.ArrayData;
                    if (path.ToUpper().EndsWith(".SLDASM"))
                    {
                        docType = (swDocumentTypes_e)swDocumentTypes_e.swDocASSEMBLY;
                    }
                    if (path.ToUpper().EndsWith(".SLDPRT"))
                    {
                        docType = (swDocumentTypes_e)swDocumentTypes_e.swDocPART;
                    }
                    int errs = 0, wrns = 0;
                    compDoc = swApp.OpenDoc6(path, (int)docType, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errs, ref wrns);
                    if (compDoc == null)
                    {
                        compDoc = (ModelDoc2)comp.GetModelDoc2();
                    }
                    if (compDoc == null)
                    {
                        swApp.SendMsgToUser2("Не могу загрузить " + path, 4, 2);
                        swApp.ExitApp();
                        System.Environment.Exit(0);
                    }
                    configuration = (string)comp.ReferencedConfiguration;
                    swModelDocExt = (ModelDocExtension)compDoc.Extension;
                    prpMgr        = (CustomPropertyManager)swModelDocExt.get_CustomPropertyManager(configuration);

                    prpMgr.Get4("Формат", true, out valOut, out _);
                    component.format = valOut;
                    prpMgr.Get4("Обозначение", true, out valOut, out _);
                    component.designation = valOut;
                    prpMgr.Get4("Наименование", true, out valOut, out _);
                    component.name = valOut;
                    prpMgr.Get4("Примечание", true, out valOut, out _);
                    component.note = valOut;
                    prpMgr.Get4("Раздел", true, out valOut, out _);
                    component.chapter = valOut;
                    prpMgr.Get4("Перв.Примен.", true, out valOut, out _);
                    component.included = valOut;

                    if ((component.chapter == "Стандартные изделия") | (component.chapter == "Прочие изделия"))
                    {
                        prpMgr.Get4("Документ на поставку", true, out valOut, out _);
                        component.doc  = valOut;
                        component.type = component.name.Substring(0, component.name.IndexOf((char)32));
                    }

                    component.x        = Math.Round((aTrans[9] * 1000), 2);
                    component.y        = Math.Round((aTrans[10] * 1000), 2);
                    component.z        = Math.Round((aTrans[11] * 1000), 2);
                    component.rotation = Euler(aTrans);
                    component.quantity = 1;

                    coll.Add(component);
                }
            }

            foreach (Comp k in coll)
            {
                if (k.chapter != "Сборочные единицы" & k.chapter != "Детали" & k.chapter != "Документация" & k.chapter != "Комплекты")
                {
                    k.format = "";
                }

                if (k.chapter != "Сборочные единицы" & k.chapter != "Детали" & k.chapter != "Документация" & k.chapter != "Комплекты" & k.chapter != "Стандартные изделия")
                {
                    k.designation = "";
                }

                if (k.format.Contains("*)"))
                {
                    k.note   = k.format.Substring(2);
                    k.format = "*)";
                }
            }

            return(coll);
        }
Exemplo n.º 28
0
 /// <summary>
 /// Возвращает название типа документа
 /// </summary>
 /// <param name="type">Тип</param>
 /// <returns>"Сборка", "Деталь", "Чертеж" или ""</returns>
 private string getDocTypeName(swDocumentTypes_e type)
 {
     switch (type)
     {
         case swDocumentTypes_e.swDocASSEMBLY:
             return "Сборка";
         case swDocumentTypes_e.swDocPART:
             return "Деталь";
         case swDocumentTypes_e.swDocDRAWING:
             return "Чертеж";
         default:
             return "";
     }
 }
        /// <summary>
        /// 后台创建文档
        /// </summary>
        /// <param name="sldWorks"></param>
        /// <param name="hidden"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static ModelDoc2 CreateDocument
            (this ISldWorks sldWorks, bool hidden = true, swDocumentTypes_e type = swDocumentTypes_e.swDocPART)
        {
            try
            {
                if (hidden)
                {
                    sldWorks.DocumentVisible(false, (int)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 (string.IsNullOrEmpty(templatePath))
                {
                    throw new FileNotFoundException(string.Format("未找到此种类型的模板文件:{0}", type.ToString()));
                }

                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);
                }

                //TODO:设置替换字符串
                var doc = (ModelDoc2)sldWorks.NewDocument(templatePath, (int)swDwgPaperSizes_e.swDwgPaperA4size, 1, 1);
                if (hidden)
                {
                    doc.Visible = false;
                    sldWorks.DocumentVisible(false, (int)type);
                }

                /*
                 * ModelView myModelView = null;
                 * myModelView = ((ModelView)(doc.ActiveView));
                 * myModelView.FrameLeft = 0;
                 * myModelView.FrameTop = 0;
                 * myModelView = ((ModelView)(doc.ActiveView));
                 *
                 * myModelView.FrameState = ((int)(swWindowState_e.swWindowMinimized));
                 */
                return(doc);
            }
            finally
            {
                if (hidden)
                {
                    sldWorks.DocumentVisible
                        (true,
                        (int)
                        type);
                }
            }
        }
Exemplo n.º 30
0
 /// <summary>
 /// Пропускать ли файл при обработке
 /// </summary>        
 private bool skipFile(swDocumentTypes_e type)
 {
     switch (type)
     {
         case swDocumentTypes_e.swDocASSEMBLY:
             return (!cbAsm.Checked);
         case swDocumentTypes_e.swDocPART:
             return (!cbPart.Checked);
         case swDocumentTypes_e.swDocDRAWING:
             return (!cbDrw.Checked);
         default:
             return true;
     }
 }
Exemplo n.º 31
0
        /// <summary>
        /// action for specific type components
        /// </summary>
        /// <param name="doc">assemblydoc instance</param>
        /// <param name="action">action you need todo</param>
        /// <param name="documentTypes">the doc type whick define with type of <see cref="swDocumentTypes_e"/></param>
        /// <param name="topOnly"></param>
        public static void UsingAllComponents(this  AssemblyDoc doc, Action <Component2> action, swDocumentTypes_e documentTypes, bool topOnly = false)
        {
            var comps = doc.GetComponents(topOnly) as Object[];

            foreach (Component2 comp in comps)
            {
                if (comp.GetCompType() == documentTypes)
                {
                    action(comp);
                }
            }
        }
Exemplo n.º 32
0
 /// <summary>
 /// Run this function after this.Document is populated. It fills two ref vars with swDocumentTypes_e.
 /// </summary>
 /// <param name="d">The document type.</param>
 /// <param name="od">The top-level document type.</param>
 private void GetTypes(ref swDocumentTypes_e d, ref swDocumentTypes_e od)
 {
     swDocumentTypes_e docT = (swDocumentTypes_e)Document.GetType();
       ModelDoc2 overDoc = (ModelDoc2)_swApp.ActiveDoc;
       swDocumentTypes_e overDocT = (swDocumentTypes_e)overDoc.GetType();
       if ((docT != swDocumentTypes_e.swDocDRAWING && swSelMgr != null) && swSelMgr.GetSelectedObjectCount2(-1) > 0) {
     Component2 comp = (Component2)swSelMgr.GetSelectedObjectsComponent4(1, -1);
     if (comp != null) {
       ModelDoc2 cmd = (ModelDoc2)comp.GetModelDoc2();
       docT = (swDocumentTypes_e)cmd.GetType();
       prop.GetPropertyData(comp);
       comp = null;
     } else {
       prop.GetPropertyData(Document);
     }
       } else {
     swSelMgr = null;
     prop.GetPropertyData(Document);
       }
       d = docT;
       od = overDocT;
 }
 public static bool IsSpecType(this IModelDoc2 doc, swDocumentTypes_e type)
 {
     return(doc.GetTypeEx() == type);
 }
        public static ModelDoc2 CreateHiddenDocument
            (this ISldWorks sldWorks, bool hidden = true, swDocumentTypes_e type = swDocumentTypes_e.swDocPART)
        {
            try
            {

                if (hidden)
                    sldWorks.DocumentVisible(false, (int)type);

                var partTemplateName = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);
                var doc = (ModelDoc2)sldWorks.NewDocument(partTemplateName, (int)swDwgPaperSizes_e.swDwgPaperA4size, 1, 1);
                doc.Visible = false;

                /*
                ModelView myModelView = null;
                myModelView = ((ModelView)(doc.ActiveView));
                myModelView.FrameLeft = 0;
                myModelView.FrameTop = 0;
                myModelView = ((ModelView)(doc.ActiveView));

                myModelView.FrameState = ((int)(swWindowState_e.swWindowMinimized));
                */
                return doc;
            }
            finally
            {
                if (hidden)
                    sldWorks.DocumentVisible
                        (true,
                            (int)
                                type);

            }

        }
Exemplo n.º 35
0
        /// <summary>
        /// Overgrown monster function that does everything. We need some refactoring here.
        /// </summary>
        public void ConnectSelection()
        {
            if (Properties.Settings.Default.IdiotLight)
            {
                if (PartSetup && mrb.IsDirty)
                {
                    if (System.Windows.Forms.MessageBox.Show(@"Save property changes?", @"Properties changed", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        Write();
                    }
                }
                if (DrawSetup && drb.IsDirty)
                {
                    if (System.Windows.Forms.MessageBox.Show(@"Save property changes?", @"Properties changed", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        Write();
                    }
                }
            }

            // Since I create objects and just toss them out liberally, I want to force garbage collection.
            // I think this leaves fewer GDI objects around. (This seems to be a good thing)
            System.GC.Collect(2, GCCollectionMode.Forced);
            prop.CutlistID = 0;
            if (Document != null)
            {
                // ignore clicks on the same object
                if (Document != md_last)
                {
                    // Blow out the propertyset so we can get new ones.
                    prop.Clear();

                    Enabled = true;
                    AddHash();

                    // what sort of doc is open?
                    swDocumentTypes_e docT     = swDocumentTypes_e.swDocNONE;
                    swDocumentTypes_e overDocT = swDocumentTypes_e.swDocNONE;
                    GetTypes(ref docT, ref overDocT);
                    switch (overDocT)
                    {
                    case swDocumentTypes_e.swDocASSEMBLY:
                        DisconnectAssemblyEvents();
                        SetupAssy((ModelDoc2)_swApp.ActiveDoc);
                        // a switch in a switch!
                        switch (docT)
                        {
                        case swDocumentTypes_e.swDocASSEMBLY:
                            regen_ok = true;
                            if (!PartSetup)
                            {
                                SetupPart();
                            }
                            if (!PartEventsAssigned)
                            {
                                ConnectPartEvents(prop.modeldoc);
                                PartSetup = true;
                            }
                            mrb.Update(ref prop);
                            break;

                        case swDocumentTypes_e.swDocDRAWING:
                            break;

                        case swDocumentTypes_e.swDocNONE:
                            break;

                        case swDocumentTypes_e.swDocPART:
                            regen_ok = true;
                            if (!PartSetup)
                            {
                                // ClearControls(this); // <-- redundant
                                // setup
                                SetupPart(prop.modeldoc);
                                // link
                                mrb.Update(ref prop);
                            }
                            else
                            {
                                DisconnectPartEvents();
                                ConnectPartEvents(prop.modeldoc);
                                PartSetup = true; // OK, this isn't how I meant to use this.
                                // or just link
                                mrb.Update(ref prop);
                            }
                            break;

                        case swDocumentTypes_e.swDocSDM:
                            break;

                        default:
                            break;
                        }
                        break;

                    case swDocumentTypes_e.swDocDRAWING:
                        regen_ok = false;
                        ClearControls(this);
                        SetupDrawing();
                        break;

                    case swDocumentTypes_e.swDocNONE:
                        SetupOther();
                        break;

                    case swDocumentTypes_e.swDocPART:
                        regen_ok = true;
                        if (!PartSetup)
                        {
                            // ClearControls(this); // <-- redundant
                            // setup
                            SetupPart(prop.modeldoc);
                            // link
                            mrb.Update(ref prop);
                        }
                        else
                        {
                            DisconnectPartEvents();
                            ConnectPartEvents(prop.modeldoc);
                            PartSetup = true; // OK, this isn't how I meant to use this.
                            // or just link
                            mrb.Update(ref prop);
                        }

                        break;

                    case swDocumentTypes_e.swDocSDM:
                        break;

                    default:
                        SetupOther();
                        break;
                    }
                }
                md_last = Document;
            }
            else
            {
                Enabled = false;
            }
#if EXPERIMENTAL
            if (Document != null)
            {
                Feature f        = (Feature)Document.FirstFeature();
                string  typeName = f.GetTypeName2();
                do
                {
                    f.GetNextSubFeature();
                    typeName = f.GetTypeName2();
                } while (typeName.ToUpper().Contains("FILE"));
                if (typeName != string.Empty)
                {
                    int res0 = SwApp.AddMenuPopupItem4(
                        (int)SolidWorks.Interop.swconst.swDocumentTypes_e.swDocASSEMBLY,
                        cookie,
                        typeName,
                        "Uaaaaaaaaaaaaaaaaa.........",
                        "donothing(1)",
                        "enablemethod(1)",
                        "pow",
                        "bip;bop"
                        );
                    int res1 = SwApp.AddMenuPopupItem4(
                        (int)SolidWorks.Interop.swconst.swDocumentTypes_e.swDocASSEMBLY,
                        cookie,
                        typeName,
                        "Ummmmmmmmmmmmmmm.........",
                        "donothing(2)",
                        "enablemethod(0)",
                        "pow",
                        "bip;bop"
                        );
                    int res2 = SwApp.AddMenuPopupItem(
                        (int)SolidWorks.Interop.swconst.swDocumentTypes_e.swDocASSEMBLY,
                        (int)SolidWorks.Interop.swconst.swSelectType_e.swSelBODYFEATURES,
                        typeName,
                        "donothing(2)",
                        "bip;bop"
                        );
                    (SwApp.Frame() as Frame).SetStatusBarText(
                        string.Format("Runtime Command IDs: {0}, {1}, {2} | Feature: {3}", res0, res1, res2, typeName)
                        );
                }
            }
#endif
        }