Exemple #1
0
        public View GetFirstView(SldWorks sw)
        {
            ModelDoc2  swModel = (ModelDoc2)sw.ActiveDoc;
            DrawingDoc d       = (DrawingDoc)swModel;
            View       v;

            string[] shtNames = (String[])swDraw.GetSheetNames();
            string   message  = string.Empty;

            //This should find the first page with something on it.
            IsTarget = IsTargetDrawing((sw.ActiveDoc as DrawingDoc).Sheet[shtNames[0]]);
            int x = 0;

            do
            {
                try {
                    d.ActivateSheet(shtNames[x]);
                } catch (IndexOutOfRangeException e) {
                    throw new IndexOutOfRangeException("Went beyond the number of sheets.", e);
                } catch (Exception e) {
                    throw e;
                }
                v = (View)d.GetFirstView();
                v = (View)v.GetNextView();
                x++;
            } while ((v == null) && (x < d.GetSheetCount()));

            message = (string)v.GetName2() + ":\n";

            if (v == null)
            {
                throw new Exception("I couldn't find a model anywhere in this document.");
            }
            return(v);
        }
        public void CheckDrawingDoc()
        {
            try
            {
                _swApp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                _swModel = _swApp.ActiveDoc;

                _swDraw = (DrawingDoc)_swModel;

                // Получение первого листа
                _swSheet           = _swDraw.GetCurrentSheet();
                StrActiveSheetName = _swSheet.GetName();

                // Узнаем имя активного листа
                _vSheetNames = _swDraw.GetSheetNames();
                _swDraw.ActivateSheet(_vSheetNames[0]);
                _swSheet = _swDraw.GetCurrentSheet();

                _swView = _swDraw.GetFirstView();

                if (_swSheet.CustomPropertyView == "По умолчанию" | _swSheet.CustomPropertyView == "Default")
                {
                    _swView = _swView.GetNextView();
                }

                _swModel = _swView.ReferencedDocument;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private string GetSheetFormat(ModelDoc2 m)
        {
            DrawingDoc d = (DrawingDoc)m;

            string[] sht_names = (string[])d.GetSheetNames();
            Sheet    s         = d.get_Sheet(sht_names[0]);

            return(s.GetTemplateName());
        }
Exemple #4
0
        /// <summary>
        /// Execute a function on each page.
        /// </summary>
        /// <param name="f">Layer choosing function.</param>
        public void CorrectLayers(selectLayer f)
        {
            DrawingDoc d      = (DrawingDoc)PropertySet.SwApp.ActiveDoc;
            Sheet      curSht = (Sheet)d.GetCurrentSheet();

            string[] shts = (string[])d.GetSheetNames();
            foreach (string s in shts)
            {
                f();
            }
            d.ActivateSheet(curSht.GetName());
        }
Exemple #5
0
        private void GetData(DrawingDoc swDraw)
        {
            // var swDraw = (DrawingDoc) swModel;

            //  var ModelDoc

            var getFirstView = (View)swDraw.GetFirstView();

            MessageBox.Show(getFirstView.ReferencedDocument.GetTitle());


            swDraw.ResolveOutOfDateLightWeightComponents();
            swDraw.ForceRebuild();

            // Движение по листам
            var vSheetName = (string[])swDraw.GetSheetNames();

            foreach (var name in vSheetName)
            {
                swDraw.ResolveOutOfDateLightWeightComponents();
                var swSheet = swDraw.Sheet[name];
                swDraw.ActivateSheet(swSheet.GetName());

                if ((!swSheet.IsLoaded()))
                {
                    continue;
                }

                var sheetviews1 = (object[])swSheet.GetViews();
                var firstView1  = (View)sheetviews1[0];
                var baseView1   = firstView1.IGetBaseView();
                var dispData1   = (IModelDoc2)baseView1.ReferencedDocument;
                MessageBox.Show(dispData1.GetTitle());

                try
                {
                    var sheetviews = (object[])swSheet.GetViews();
                    var firstView  = (View)sheetviews[0];
                    firstView.SetLightweightToResolved();

                    var baseView = firstView.IGetBaseView();
                    var dispData = (IModelDoc2)baseView.ReferencedDocument;

                    MessageBox.Show(dispData.GetTitle());
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }
        private void FormLoad_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _swApp              = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                _swModel            = (ModelDoc2)_swApp.ActiveDoc;
                _swDraw             = (DrawingDoc)_swModel;
                _swSheet            = (Sheet)_swDraw.GetCurrentSheet();
                _strActiveSheetName = _swSheet.GetName();
                _vSheetNames        = _swDraw.GetSheetNames();

                CmdRevMethod(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "; " + ex.StackTrace);
            }
        }
Exemple #7
0
        private static void SheetNumering(ModelDoc2 swModel, DrawingDoc swDraw)
        {
            int shi = 0;

            var swSheetNames = (string[])swDraw.GetSheetNames();
            foreach (var swSheetName in swSheetNames)
            {
                if (shi == 1)
                {
                    swDraw.ActivateSheet(swSheetName);
                    AddTextBlock(swModel, swDraw, "Лист 1 из 2", 0.26, 0.2, 0, 0.004, 0);
                }
                else
                {
                    if (shi == 2)
                    {
                        swDraw.ActivateSheet(swSheetName);
                        AddTextBlock(swModel, swDraw, "Лист 2 из 2", 0.26, 0.2, 0, 0.004, 0);
                    }
                }
                shi++;
            }
        }
        public void check()
        {
            int m = 0;

            //swapp = CreateObject("SldWorks.Application")
            swapp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swmodel = swapp.ActiveDoc;

            // Проверка открытого документа
            if (swmodel == null)
            {
                swapp.SendMsgToUser("Откройте чертеж");
                return;
            }
            //Or swDocumentTypes_e.swDocASSEMBLY
            if (swmodel.GetType() != (int)swDocumentTypes_e.swDocDRAWING)
            {
                swapp.SendMsgToUser("Откройте чертеж");
                return;
            }

            if (string.IsNullOrEmpty(swmodel.GetPathName()))
            {
                swapp.SendMsgToUser("Сохраните чертеж!");
                Close();
                return;
            }

            swDraw = (DrawingDoc)swmodel;

            // Получение первого листа
            swSheet            = swDraw.GetCurrentSheet();
            strActiveSheetName = swSheet.GetName();
            // Узнаем имя активного листа
            vSheetNames = swDraw.GetSheetNames();
            ok          = swDraw.ActivateSheet(vSheetNames[0]);
            swSheet     = swDraw.GetCurrentSheet();

            swView = swDraw.GetFirstView();
            //m = 0

            //Debug.Print(swSheet.CustomPropertyView);

            if (swSheet.CustomPropertyView == "По умолчанию" | swSheet.CustomPropertyView == "Default")
            {
                swView = swView.GetNextView();
                // Получаем первый вид
            }
            else
            {
                while (!(swView == null))
                {
                    if (swView.GetName2() == swSheet.CustomPropertyView)
                    {
                        m = 1;
                        break;
                    }
                    swView = swView.GetNextView();
                }
                if (m == 0)
                {
                    swView = swDraw.GetFirstView();
                    swView = swView.GetNextView();
                    swapp.SendMsgToUser("Не удалось определить вид из свойств листа. Ипользуется первый вид.");
                }
            }

            if (swView == null)
            {
                swapp.SendMsgToUser("Отсутсвует модель!");
                // Возвращение активного листа
                ok = swDraw.ActivateSheet(strActiveSheetName);
                return;
            }

            if (swView.ReferencedDocument == null)
            {
                swapp.SendMsgToUser("Отсутсвует модель!");
                // Возвращение активного листа
                ok = swDraw.ActivateSheet(strActiveSheetName);
                return;
            }

            swmodel = swView.ReferencedDocument;
            if (swmodel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                swapp.SendMsgToUser("Чертеж должен быть сборочным!");
                // Возвращение активного листа
                ok = swDraw.ActivateSheet(strActiveSheetName);
                return;
            }
        }
        public void LoadDataGridConfig()
        {
            try
            {
                //SelectionMgr swSelMgr;
                //Configuration swConfig; ;
                string   sConfigName;
                object[] vConfNameArr;

                //swapp = CreateObject("SldWorks.Application")
                swapp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                swmodel = swapp.ActiveDoc;

                swDraw = (DrawingDoc)swmodel;

                swSheet            = swDraw.GetCurrentSheet();
                strActiveSheetName = swSheet.GetName();

                vSheetNames = swDraw.GetSheetNames();
                swDraw.ActivateSheet(vSheetNames[0]);

                swSheet = swDraw.GetCurrentSheet();
                swView  = swDraw.GetFirstView();

                // Получаем параметры модели
                if (swSheet.CustomPropertyView == "По умолчанию" | swSheet.CustomPropertyView == "Default")
                {
                    swView = swView.GetNextView();
                }

                sConfigName = swView.ReferencedConfiguration;

                swmodel = swView.ReferencedDocument;
                swmodel.GetConfigurationByName(sConfigName);

                vConfNameArr = swmodel.GetConfigurationNames();

                // Конфигурация
                for (var i = 0; i <= vConfNameArr.GetUpperBound(0); i++)
                {
                    DataGridConfig.Rows.Add(ColChB.Selected, vConfNameArr[i]);
                }

                //Get customProperty from Assy
                CustomPropertyManager swCustProp = default(CustomPropertyManager);
                string valOut      = "";
                string Number      = "";
                string Description = "";

                swCustProp = swmodel.Extension.CustomPropertyManager[""];

                swCustProp.Get2("Обозначение", out valOut, out Number);
                swCustProp.Get2("Наименование", out valOut, out Description);

                addinform = new addincheckbox();
                try
                {
                    //Fill DataGriad
                    foreach (string line in System.IO.File.ReadAllLines("C:\\Program Files\\SW-Complex\\doc.txt"))
                    {
                        addinform.DGDoc.Rows.Add(addinform.DocChb.Selected, line);
                    }
                }
                catch (Exception ex)
                {
                    //Interaction.MsgBox("Отсутствует SW-Complex или Doc.txt");
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #10
0
        public void GetXMLfromBOM()
        {
            swapp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swmodel = swapp.ActiveDoc;

            swModelDocExt = swmodel.Extension;

            //создаем MemoryStream, в который будем писать XML
            var myMemoryStream = new MemoryStream();

            //создаем XmlTextWriter, указываем объект – myMemoryStream, в который будем писать XML, и кодировку
            try
            {
                var myXml = new System.Xml.XmlTextWriter("C:\\Program Files\\SW-Complex\\SP-Temp.xml", System.Text.Encoding.UTF8);
                swDraw      = (DrawingDoc)swmodel;
                vSheetNames = swDraw.GetSheetNames();
                ok          = swDraw.ActivateSheet(vSheetNames[0]);
                swView      = swDraw.GetFirstView();

                // Получаем параметры модели
                swView  = swView.GetNextView();
                swmodel = swView.ReferencedDocument;

                //swSelMgr = swDraw.SelectionManager;

                myXml.WriteStartDocument();
                myXml.Formatting = System.Xml.Formatting.Indented;

                //длина отступа
                myXml.Indentation = 2;
                vConfName         = swmodel.GetConfigurationNames();


                swapp   = new SldWorks();
                swmodel = swapp.ActiveDoc;

                Feature swFeat = swmodel.FirstFeature();

                while ((swFeat != null))
                {
                    if (swFeat.GetTypeName() == "BomFeat")
                    {
                        swFeat.Select(true);
                        swBomFeature = swFeat.GetSpecificFeature2();
                    }
                    swFeat = swFeat.GetNextFeature();
                }

                //////////////////////////////////////////////////////
                //
                //           GetPropertyBomTableFromDrawDoc
                //
                //////////////////////////////////////////////////////

                object          vConfigurations   = null;
                object          vVisibility       = null;
                bool            bGetVisible       = false;
                long            lNumRow           = 0;
                long            lNumColumn        = 0;
                int             lRow              = 0;
                TableAnnotation swTableAnnotation = default(TableAnnotation);
                ModelDoc2       swDocument        = default(ModelDoc2);
                AssemblyDoc     swAssembly        = default(AssemblyDoc);
                int             lStartRow         = 0;
                string          strItemNumber     = "";
                string          strPartNumber     = "";
                string          strDescription    = "";

                var strDocumentName = swBomFeature.GetReferencedModelName();

                swDocument = swapp.GetOpenDocumentByName(strDocumentName);
                swAssembly = (AssemblyDoc)swDocument;

                //swBOMTableAnnotation = swBomFeature.GetTableAnnotations(0)
                var swBomTableAnnotation = (BomTableAnnotation)swBomFeature.GetTableAnnotations()[0];

                swTableAnnotation = (TableAnnotation)swBomTableAnnotation;

                lNumRow    = swTableAnnotation.RowCount;
                lNumColumn = swTableAnnotation.ColumnCount;

                lStartRow = 1;

                //If (Not (swTableAnnotation.TitleVisible = False)) Then
                if (swTableAnnotation.TitleVisible == false)
                {
                    lStartRow = 2;
                }

                bGetVisible     = false;
                vConfigurations = swBomFeature.GetConfigurations(bGetVisible, vVisibility);

                //swTableAnnotation = swTableAnnotation;

                ///////////////////////////////////////////////////////////////////

                swSheet            = swDraw.GetCurrentSheet();
                strActiveSheetName = swSheet.GetName();
                vSheetNames        = swDraw.GetSheetNames();
                ok      = swDraw.ActivateSheet(vSheetNames[0]);
                swSheet = swDraw.GetCurrentSheet();
                swView  = swDraw.GetFirstView();

                if (swSheet.CustomPropertyView == "По умолчанию" | swSheet.CustomPropertyView == "Default")
                {
                    swView = swView.GetNextView();
                }

                // get custom property

                var valout  = ""; //Обозначение
                var valout1 = ""; //Наименование


                CustomPropertyManager swCustProp = default(CustomPropertyManager);
                var resolvedValOut  = "";
                var resolvedValOut1 = "";
                //string resolvedValOut3 = "";
                //string resolvedValOut4 = "";
                //string resolvedValOut5 = "";
                swCustProp = swmodel.Extension.CustomPropertyManager[""];
                swCustProp.Get2("Обозначение", out valout, out resolvedValOut);
                swCustProp.Get2("Description", out valout1, out resolvedValOut1);

                // переменные для колонок

                int Jj = 0;             // наименование
                int aa = 0;             // раздел
                int oo = 0;             // обозначение
                int tt = 0;             // формат
                int yy = 0;             //
                int uu = 0;             // Код материала
                int ss = 0;             // Примечание

                string sRowStr  = null; // наименовани
                string sRowStr1 = null; // раздел
                string sRowStr2 = null; // обозначение
                string sRowStr3 = null; // формат
                string sRowStr4 = null; // ERP code
                string sRowStr5 = null; // Код материала
                string sRowStr6 = null; // Примечание

                // При выборе электромонтажа
                string Complect = "";

                if (addinform.ChkElectro1.Checked)
                {
                    Complect = "МЭ";
                }
                else if (addinform.ChkElectro2.Checked)
                {
                    Complect = "ТБ";
                }

                ////////////////////////////////////////////////////////////
                //
                //                          XML
                //
                ////////////////////////////////////////////////////////////

                //создаем элементы
                myXml.WriteStartElement("xml");
                //
                myXml.WriteStartElement("Item");

                // имя пути основного чертежа
                myXml.WriteStartElement("PathName");
                //записываем строку
                myXml.WriteString(swmodel.GetPathName());
                myXml.WriteEndElement();

                // Устанавливаем ДОК из формы добавление
                myXml.WriteStartElement("doc");
                //
                myXml.WriteStartElement("Обозначение");
                //записываем строку
                myXml.WriteString(resolvedValOut + "CБ");
                myXml.WriteEndElement();
                //
                myXml.WriteStartElement("Наименование");
                myXml.WriteString("Сборочный чертеж");
                myXml.WriteEndElement();
                //
                myXml.WriteEndElement(); //doc

                //dynamic CheckedRows2 = (from Rows in addinform.DGDoc.Rows.Cast<DataGridViewRow>()where Convert.ToBoolean(Rows.Cells(0).Value) == true).ToList;

                dynamic CheckedRows2 = (from Rows in addinform.DGDoc.Rows.Cast <DataGridViewRow>() where Convert.ToBoolean(Rows.Cells[0].Value.ToString()) select Rows).ToList();


                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                foreach (DataGridViewRow row in CheckedRows2)
                {
                    sb.AppendLine(row.Cells[1].Value.ToString());
                    sb.ToString();

                    //Оставляем первые две буквы для обозначения разделитель

                    var literal   = row.Cells[1].Value.ToString();
                    var substring = literal.Substring(0, 2);

                    var literal2   = row.Cells[1].Value.ToString();
                    var substring2 = literal2.Substring(5);

                    myXml.WriteStartElement("doc");
                    ///
                    myXml.WriteStartElement("Обозначение");
                    //записываем строку
                    myXml.WriteString(resolvedValOut + substring);
                    myXml.WriteEndElement();
                    ///
                    myXml.WriteStartElement("Наименование");
                    myXml.WriteString(substring2);
                    myXml.WriteEndElement();
                    ///
                    myXml.WriteEndElement();
                    //doc
                }


                //<------------- Elec
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro1.Checked == false & addinform.ChkElectro2.Checked == false)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec

                    myXml.WriteString("Устанавливают при электромонтаже");
                    myXml.WriteEndElement();
                    //Elec
                }

                //<------------- ChkElectro1
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro1.Checked == true)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec
                    myXml.WriteString("Устанавливают по " + resolvedValOut + Complect);
                    myXml.WriteEndElement();
                    //Elec
                }

                //<------------- ChkElectro2
                if (addinform.ChkElectro.Checked == true & addinform.ChkElectro2.Checked == true)
                {
                    myXml.WriteStartElement("Elec");
                    //Elec
                    myXml.WriteString("Устанавливают по " + resolvedValOut + Complect);
                    myXml.WriteEndElement();
                    //Elec
                }

                //
                myXml.WriteStartElement("Обозначение");
                //записываем строку
                myXml.WriteString(resolvedValOut);
                myXml.WriteEndElement();
                ///
                myXml.WriteStartElement("Наименование");
                myXml.WriteString(resolvedValOut1);
                myXml.WriteEndElement();

                //\reference
                myXml.WriteStartElement("references");

                // ВЫГРУЖАЕМ ВЫБРАННЫЕ КОНФИГУРАЦИИ

                dynamic CheckedRows           = (from Rows in DataGridConfig.Rows.Cast <DataGridViewRow>() where Convert.ToBoolean(Rows.Cells[0].Value.ToString()) select Rows).ToList();
                System.Text.StringBuilder sb2 = new System.Text.StringBuilder();

                foreach (DataGridViewRow row in CheckedRows)
                {
                    sb2.AppendLine(row.Cells[1].Value.ToString());

                    swmodel = swView.ReferencedDocument;
                    var configuration = swView.ReferencedConfiguration;

                    var           sConfigName = swView.ReferencedConfiguration;
                    Configuration swConfig    = swmodel.GetConfigurationByName(sConfigName);

                    for (var i = 0; i <= vConfName.GetUpperBound(0); i++)
                    {
                        const string ucase = "";

                        if (vConfName[i] == row.Cells[1].Value.ToString())
                        {
                            configuration = vConfName[i];
                        }
                    }

                    swView.ReferencedConfiguration = sConfigName;

                    myXml.WriteStartElement("config");
                    myXml.WriteAttributeString("value", row.Cells[1].Value.ToString());


                    /////////////////////////////////////////////////////////////
                    //
                    //                           PART
                    //
                    /////////////////////////////////////////////////////////////

                    for (lRow = lStartRow; lRow <= (lNumRow - 1); lRow++)
                    {
                        if (swBomTableAnnotation.GetComponentsCount2((int)lRow, row.Cells[1].Value.ToString(), out strItemNumber, out strPartNumber) > 0)
                        {
                            myXml.WriteStartElement("part");
                            //PathNameComponent
                            string strModelPathName = null;
                            var    vModelPathNames  = swBomTableAnnotation.GetModelPathNames((int)lRow, out strItemNumber, out strPartNumber);
                            if (((vModelPathNames != null)))
                            {
                                myXml.WriteStartElement("PathNameComponent");
                                foreach (var vModelPathName_loopVariable in vModelPathNames)
                                {
                                    var vModelPathName = vModelPathName_loopVariable;
                                    strModelPathName = vModelPathName;
                                    myXml.WriteString(strModelPathName);
                                }
                                myXml.WriteEndElement();
                            }
                            //'\ Row
                            myXml.WriteStartElement("Row");
                            myXml.WriteString(Convert.ToString(lRow - lStartRow + 1));
                            myXml.WriteEndElement();
                            vModelPathNames = swBomTableAnnotation.GetModelPathNames((int)lRow, out strItemNumber, out strPartNumber);
                            //\ ItemNum
                            myXml.WriteStartElement("ItemNum");
                            myXml.WriteString(strItemNumber);
                            myXml.WriteEndElement();
                            //\ раздел
                            aa = 3;
                            /// раздел
                            sRowStr1 = "";
                            sRowStr1 = sRowStr1 + swTableAnnotation.Text[lRow, aa];
                            myXml.WriteStartElement("Раздел");
                            myXml.WriteString(sRowStr1);
                            myXml.WriteEndElement();
                            //\ обозначение
                            oo = 1;
                            /// обозначение
                            sRowStr2 = "";
                            sRowStr2 = sRowStr2 + swTableAnnotation.Text[lRow, oo];
                            myXml.WriteStartElement("Обозначение");
                            myXml.WriteString(sRowStr2);
                            myXml.WriteEndElement();
                            //\ наименование
                            Jj = 2;
                            /// наименование
                            sRowStr = "";
                            sRowStr = sRowStr + swTableAnnotation.Text[lRow, Jj];
                            myXml.WriteStartElement("Наименование");
                            myXml.WriteString(sRowStr);
                            myXml.WriteEndElement();
                            //\
                            tt = 4;
                            /// формат
                            sRowStr3 = "";
                            sRowStr3 = sRowStr3 + swTableAnnotation.Text[lRow, tt];
                            myXml.WriteStartElement("Формат");
                            myXml.WriteString(sRowStr3);
                            myXml.WriteEndElement();
                            //\
                            yy = 5;
                            /// ERP code
                            sRowStr4 = "";
                            sRowStr4 = sRowStr4 + swTableAnnotation.Text[lRow, yy];
                            myXml.WriteStartElement("ERP_code");
                            myXml.WriteString(sRowStr4);
                            myXml.WriteEndElement();
                            //\
                            uu = 6;
                            /// Код материала
                            sRowStr5 = "";
                            sRowStr5 = sRowStr5 + swTableAnnotation.Text[lRow, uu];
                            myXml.WriteStartElement("Код_материала");
                            myXml.WriteString(sRowStr5);
                            myXml.WriteEndElement();
                            //\
                            ss = 7;
                            /// наименование
                            sRowStr6 = "";
                            sRowStr6 = sRowStr6 + swTableAnnotation.Text[lRow, ss];
                            myXml.WriteStartElement("Примечание");
                            myXml.WriteString(sRowStr6);
                            myXml.WriteEndElement();
                            //\

                            myXml.WriteStartElement("Количество");
                            //myXml.WriteString(swTableAnnotation.GetComponentsCount2(lRow, strConfiguration, strItemNumber, strPartNumber))
                            myXml.WriteString(Convert.ToString(swBomTableAnnotation.GetComponentsCount2(lRow, row.Cells[1].Value.ToString(), out strItemNumber, out strPartNumber)));
                            myXml.WriteEndElement();
                            myXml.WriteEndElement();
                            //config
                        }
                    }


                    myXml.WriteEndElement(); //part
                }


                myXml.WriteEndElement(); //references
                //<~~~~~~~~~~~~~~~~~~~~~~~~~~~ Get the Total Number of Rows


                Annotation      swAnn   = default(Annotation);
                TableAnnotation swTable = default(TableAnnotation);
                long            nNumRow = 0;

                swmodel = swapp.ActiveDoc;

                swView  = swDraw.GetFirstView();
                swTable = swView.GetFirstTableAnnotation();
                swAnn   = swTable.GetAnnotation();

                nNumRow = swTable.RowCount;
                myXml.WriteStartElement("TotalRows");
                myXml.WriteString(Convert.ToString(nNumRow));
                myXml.WriteEndElement();
                //end TotalRows

                myXml.WriteEndElement();
                //Item
                myXml.WriteEndElement();
                //элемент XML

                //End If
                //заносим данные в myMemoryStream
                myXml.Flush();
                myXml.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
Exemple #11
0
        public static void GetSolidObject()
        {
            swApp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swModel = swApp.ActiveDoc;

            // Проверка открытого документа
            if (swModel == null)
            {
                swApp.SendMsgToUser2("Откройте модель, сборку или чертеж!", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);

                return;
            }

            if (string.IsNullOrEmpty(swModel.GetPathName()))
            {
                swApp.SendMsgToUser2("Сохраните файл!", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);

                return;
            }

            docType = (swDocumentTypes_e)swModel.GetType();


            if (docType != swDocumentTypes_e.swDocDRAWING)
            {
                configName           = swModel.GetActiveConfiguration().Name;//при первом вызове присваеваеться активная конфигурация
                EditProp.configNames = EditProp.GetAllConfigurations();
            }
            else
            {
                #region Если открыт чертеж

                lockForConf = true;//нельзя изменить конфигурацию на формочке

                drw = (DrawingDoc)swModel;
                // Получение первого листа
                Sheet swSheet = drw.GetCurrentSheet();

                Propertiy.Format = GetFormat(swSheet);
                Propertiy.Sheets = drw.GetSheetCount().ToString();
                Propertiy.Sheet  = swSheet.GetName();
                // Узнаем имя активного листа
                string[] vSheetNames = drw.GetSheetNames();
                drw.ActivateSheet(vSheetNames[0]);
                swSheet         = drw.GetCurrentSheet();
                swView          = drw.GetFirstView();
                Propertiy.Scale = swView.ScaleRatio[0].ToString() + ":" + swView.ScaleRatio[1].ToString();

                m = 0;

                if (swSheet.CustomPropertyView == "По умолчанию" | swSheet.CustomPropertyView == "Default")
                {
                    // Получаем первый вид
                    swView = swView.GetNextView();
                }
                else
                {
                    while (swView != null)
                    {
                        if (swView.GetName2() == swSheet.CustomPropertyView)
                        {
                            m = 1;
                        }
                        swView = swView.GetNextView();
                    }
                    if (m == 0)
                    {
                        swView = drw.GetFirstView();
                        swView = swView.GetNextView();
                        swApp.SendMsgToUser2("Не удалось определить вид из свойств листа. Ипользуется первый вид.", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);
                    }
                }

                if (swView == null)
                {
                    swApp.SendMsgToUser2("Отсутсвует модель!", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);
                    // Возвращение активного листа
                    drw.ActivateSheet(Propertiy.Sheet);
                    return;
                }

                if (swView.ReferencedDocument == null)
                {
                    swApp.SendMsgToUser2("Отсутсвует модель!", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);
                    // Возвращение активного листа
                    drw.ActivateSheet(Propertiy.Sheet);
                    return;
                }
                #endregion
            }
        }
 /// <summary>
 /// Gets the sheet names of the drawing
 /// </summary>
 /// <returns></returns>
 public string[] SheetNames() => (string[])mBaseObject.GetSheetNames();
Exemple #13
0
        public string PdfLoad(string filepath, bool deep, string pathpdf)
        {
            try
            {
                SwModel = SolidWorksAdapter.SldWoksAppExemplare.OpenDoc6(filepath, (int)swDocumentTypes_e.swDocDRAWING,
                                                                         (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", 0, 0);
                SwDraw = (DrawingDoc)SwModel;

                SwDraw.ResolveOutOfDateLightWeightComponents();
                SwDraw.ForceRebuild();

                var vSheetName = (string[])SwDraw.GetSheetNames();


                foreach (var name in vSheetName)
                {
                    if (name != null)
                    {
                        SwDraw.ResolveOutOfDateLightWeightComponents();
                        var swSheet = SwDraw.Sheet[name];

                        SwDraw.ActivateSheet(swSheet.GetName());

                        if ((swSheet.IsLoaded()))
                        {
                            var sheetviews = (object[])swSheet.GetViews();

                            if (sheetviews != null)
                            {
                                var firstView = (View)sheetviews[0];

                                firstView.SetLightweightToResolved();
                            }
                        }

                        if (!deep)
                        {
                            continue;
                        }
                        var views = (object[])swSheet.GetViews();

                        if (views != null)
                        {
                            foreach (var drwView in views.Cast <View>())
                            {
                                drwView.SetLightweightToResolved();
                            }
                        }
                    }
                }

                var errors   = 0;
                var warnings = 0;
                var newpath  = pathpdf + "\\" + Path.GetFileNameWithoutExtension(SwModel.GetPathName()) + ".pdf";
                //var newpath = Path.GetFullPath(SwModel.GetPathName().Replace("slddrw".ToUpper(), "pdf"));// + Path.GetFileNameWithoutExtension(SwModel.GetPathName()) + ".pdf";
                SwModel.Extension.SaveAs(newpath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_UpdateInactiveViews, null, ref errors, ref warnings);
                SolidWorksAdapter.SldWoksAppExemplare.CloseDoc(Path.GetFileNameWithoutExtension(new FileInfo(newpath).FullName));
                //SolidWorksAdapter.KillProcsses("SLDWORKS");

                return(newpath);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                throw;
            }
        }
Exemple #14
0
        public void CheckAndUpdateGaugeNotes2()
        {
            String currPage = swDraw.GetCurrentSheet().ToString();
            Int32  shtCount = swDraw.GetSheetCount();

            String[] shtName = (String[])swDraw.GetSheetNames();

            for (int page = 0; page < shtCount; page++)
            {
                swFrame.SetStatusBarText(String.Format("Activating page {0}...", shtName[page]));
                swDraw.ActivateSheet(shtName[page]);
                swView = (View)swDraw.GetFirstView();

                while (swView != null)
                {
                    swDispDim = swView.GetFirstDisplayDimension5();

                    while (swDispDim != null)
                    {
                        swDim = (Dimension)swDispDim.GetDimension2(0);
                        swFrame.SetStatusBarText(String.Format("Processing '{0}' => '{1}'...", swDim.Name, swDim.Value.ToString()));
                        string dimtext = swDispDim.GetText((Int32)swDimensionTextParts_e.swDimensionTextCalloutBelow);
                        dimtext = dimtext.Replace(@"(", string.Empty).Replace(@")", string.Empty).Trim();
                        if (gaugeRegex.IsMatch(dimtext))
                        {
                            string[] texts_ = dimtext.Split(' ');
                            gaugeNote = Regex.Replace(texts_[texts_.Length - 1], "[0-9]", string.Empty);
                            Double og;
                            if (!Double.TryParse(swDim.GetSystemValue2("").ToString(), out og))
                            {
                                throw new GaugeSetterException("Couldn't parse dimension value.");
                            }
                            ourGauge = og / 0.0254;

                            for (int i = 0; i < Gauges.Gauge.Length; i++)
                            {
                                Double dCellVal;

                                if (!Double.TryParse(Gauges.Gauge[i].Thickness, out dCellVal))
                                {
                                    throw new GaugeSetterException("Couldn't parse gauge thickness.");
                                }
                                else

                                if (Math.Abs(ourGauge - dCellVal) < 0.00003)
                                {
                                    String gaugeCell   = String.Empty;
                                    String gaugeString = String.Empty;
                                    gaugeNotFound = false;

                                    swDispDim.ShowParenthesis = true;
                                    gaugeString = String.Format("{0} {1}", Gauges.Gauge[i].GaugeNumber, gaugeNote.ToUpper());
                                    swDispDim.SetText((int)swDimensionTextParts_e.swDimensionTextCalloutBelow, gaugeString);
                                }
                            }
                            if (gaugeNotFound)
                            {
                                if (!APathSet.SilenceGaugeErrors)
                                {
                                    StringBuilder sb = new StringBuilder("Non-standard gauge thickness detected:\n");
                                    sb.AppendFormat(get_format_txt(), swDim.Name, swView.Name, ourGauge);
                                    swApp.SendMsgToUser2(sb.ToString()
                                                         , (int)swMessageBoxIcon_e.swMbWarning
                                                         , (int)swMessageBoxBtn_e.swMbOk);
                                }
                                gaugeNotFound = false;
                            }
                        }
                        swDispDim = swDispDim.GetNext5();
                    }
                    swView = (View)swView.GetNextView();
                }
            }
            swDraw.ActivateSheet(currPage);

            if (gaugeNotFound)               // Why waste time rebuilding?
            {
                swFrame.SetStatusBarText("Rebuilding");
                swDraw.ForceRebuild();
            }
            swFrame.SetStatusBarText(String.Empty);
        }
Exemple #15
0
        public static void Start()
        {
            // Проверка открытого документа
            if (swModel == null)
            {
                swApp.SendMsgToUser2("Откройте модель, сборку или чертеж!", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);

                return;
            }

            if (string.IsNullOrEmpty(swModel.GetPathName()))
            {
                swApp.SendMsgToUser2("Сохраните файл!", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);

                return;
            }

            // Определение типа документа
            if (docType == swDocumentTypes_e.swDocDRAWING)
            {
                drw = (DrawingDoc)swModel;

                // Получение первого листа
                Sheet  swSheet            = drw.GetCurrentSheet();
                string strActiveSheetName = swSheet.GetName();

                // Узнаем имя активного листа
                string[] vSheetNames = drw.GetSheetNames();
                drw.ActivateSheet(vSheetNames[0]);
                swSheet = drw.GetCurrentSheet();
                swView  = drw.GetFirstView();

                m = 0;

                if (swSheet.CustomPropertyView == "По умолчанию" | swSheet.CustomPropertyView == "Default")
                {
                    swView = swView.GetNextView();
                    // Получаем первый вид
                }
                else
                {
                    while (swView != null)
                    {
                        if (swView.GetName2() == swSheet.CustomPropertyView)
                        {
                            m = 1;
                        }
                        swView = swView.GetNextView();
                    }
                    if (m == 0)
                    {
                        swView = drw.GetFirstView();
                        swView = swView.GetNextView();
                        swApp.SendMsgToUser2("Не удалось определить вид из свойств листа. Ипользуется первый вид.", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);
                    }
                }

                if (swView == null)
                {
                    swApp.SendMsgToUser2("Отсутсвует модель!", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);
                    // Возвращение активного листа
                    drw.ActivateSheet(strActiveSheetName);
                    return;
                }

                if (swView.ReferencedDocument == null)
                {
                    swApp.SendMsgToUser2("Отсутсвует модель!", (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);
                    // Возвращение активного листа
                    drw.ActivateSheet(strActiveSheetName);
                    return;
                }
                string sModelName = swView.GetReferencedModelName();
                Class.configuracione = swView.ReferencedConfiguration;
                swModel = swView.ReferencedDocument;
            }
        }