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);
            }
        }
Пример #2
0
        public void InsertBom()
        {
            SldWorks       swApp     = default(SldWorks);
            ModelDoc2      swModel   = default(ModelDoc2);
            SelectionMgr   swSelMgr  = default(SelectionMgr);
            FeatureManager swFeatMgr = default(FeatureManager);

            SolidWorks.Interop.sldworks.View swView;
            BomTableAnnotation swBomAnn  = default(BomTableAnnotation);
            BomFeature         swBomFeat = default(BomFeature);
            long   anchorType            = 0;
            long   bomType       = 0;
            string configuration = null;
            string tableTemplate = null;

            object     visible = null;
            DrawingDoc swDraw;
            Sheet      swSheet = default(Sheet);

            //swApp = DirectCast(Marshal.GetActiveObject("SldWorks.Application"), SldWorks)
            swApp     = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swModel   = swApp.ActiveDoc;
            swFeatMgr = swModel.FeatureManager;
            swDraw    = (DrawingDoc)swModel;
            swSheet   = swDraw.GetCurrentSheet();

            swModel.Extension.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swDetailingLayer, (int)swUserPreferenceOption_e.swDetailingBillOfMaterial, "");
            //ecли FALSE вставляются все конфигурации
            swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swOneConfigOnlyTopLevelBom, 0, false);

            swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swBomTableDontAddQTYNextToConfigName, 0, true);
            swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDontCopyQTYColumnNameFromTemplate, 0, true);
            //swDraw.SetUserPreferenceIntegerValue(swBomTableZeroQuantityDisplay, swZeroQuantityBlank);

            //Select View
            swModel.ClearSelection2(true);
            swView = swDraw.GetCurrentSheet().GetViews()[0];

            //Insert BOM Table
            anchorType = (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft;
            bomType    = (int)swBomType_e.swBomType_TopLevelOnly;

            swModel.ClearSelection2(true);

            configuration = "";

            tableTemplate = "C:\\Program Files\\SW-Complex\\Template.sldbomtbt";

            swBomAnn = swView.InsertBomTable2(false, -0, -0, (int)anchorType, (int)bomType, configuration, tableTemplate);

            swFeatMgr.UpdateFeatureTree();

            swBomFeat = swBomAnn.BomFeature;

            var Names = swBomFeat.GetConfigurations(false, visible);

            visible = true;
            swBomFeat.SetConfigurations(true, visible, Names);
        }
Пример #3
0
        public void CorrectLayers(string rev, selectLayer f)
        {
            Sheet curSht = (Sheet)swDraw.GetCurrentSheet();

            string[] shts = (string[])swDraw.GetSheetNames();
            foreach (string s in shts)
            {
                swFrame.SetStatusBarText("Showing correct revs on " + s + "...");
                swDraw.ActivateSheet(s);
                f(rev);
            }
            swDraw.ActivateSheet(curSht.GetName());
        }
 /// <summary>
 /// Gets the name of the currently active sheet
 /// </summary>
 /// <returns></returns>
 public string CurrentActiveSheet()
 {
     using (var sheet = new DrawingSheet((Sheet)mBaseObject.GetCurrentSheet(), this))
     {
         return(sheet.SheetName);
     }
 }
Пример #5
0
        public double[] GetSheetSize(DrawingDoc d)
        {
            Sheet sht = (Sheet)d.GetCurrentSheet();

            double[] sp     = (double[])sht.GetProperties();
            double[] s_size = { sp[5], sp[6] };
            return(s_size);
        }
Пример #6
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());
        }
Пример #7
0
        /// <summary>
        /// 添加尺寸
        /// </summary>
        /// <param name="dimensionType">添加尺寸类型</param>
        /// <param name="swDrawDoc"></param>
        /// <param name="swModel"></param>
        private void AddDimension(string dimensionType, DrawingDoc swDrawDoc, ModelDoc2 swModel)
        {
            ModelDocExtension swModelDocExt = (ModelDocExtension)swModel.Extension;

            //swDrawDoc.AutoDimension((int)swAutodimEntities_e.swAutodimEntitiesBasedOnPreselect, (int)swAutodimScheme_e.swAutodimSchemeBaseline, (int)swAutodimHorizontalPlacement_e.swAutodimHorizontalPlacementAbove, (int)swAutodimScheme_e.swAutodimSchemeBaseline, (int)swAutodimVerticalPlacement_e.swAutodimVerticalPlacementRight);
            if (addDimensionNo)
            {
                return;
            }
            else if (addDimensionAuto)
            {
                _currentSheet = (Sheet)swDrawDoc.GetCurrentSheet();
                swDrawDoc.ActivateSheet(_currentSheet.GetName());
                //swDrawDoc.AutoDimension((int)swAutodimEntities_e.swAutodimEntitiesBasedOnPreselect, (int)swAutodimScheme_e.swAutodimSchemeBaseline, (int)swAutodimHorizontalPlacement_e.swAutodimHorizontalPlacementAbove, (int)swAutodimScheme_e.swAutodimSchemeBaseline, (int)swAutodimVerticalPlacement_e.swAutodimVerticalPlacementRight);
                object[] array3 = (object[])swDrawDoc.InsertModelAnnotations3((int)swImportModelItemsSource_e.swImportModelItemsFromEntireModel, (int)swInsertAnnotation_e.swInsertDimensionsMarkedForDrawing, true, true, false, false);
            }
        }
        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);
            }
        }
Пример #9
0
        public int LoadEnable()
        {
            try
            {
                int functionReturnValue = 0;
                swModel = SwApp.ActiveDoc;
                try
                {
                    if (swModel.GetType() != (int)swDocumentTypes_e.swDocDRAWING)
                    {
                        functionReturnValue = 0;
                    }
                    else
                    {
                        _swDraw             = (DrawingDoc)swModel;
                        swSheet             = _swDraw.GetCurrentSheet();
                        swView              = _swDraw.GetFirstView();
                        functionReturnValue = 1;
                    }

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

                    swModel = swView.ReferencedDocument;
                    if (swModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)
                    {
                        functionReturnValue = 0;
                    }
                }
                catch
                {
                    functionReturnValue = 0;
                }
                return(functionReturnValue);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
Пример #10
0
 private void NoteAlign()
 {
     if (ChkAlign.Checked == Convert.ToBoolean(1))
     {
         swNote.Angle = 0;
         boolstatus   = swNote.SetBalloon(0, 0);
         swAnn        = swNote.GetAnnotation();
         // Определение координат заметки
         swSheet       = swDraw.GetCurrentSheet();
         vSheetProps   = swSheet.GetProperties()[5];
         NoteSetWidth  = Convert.ToDouble(vSheetProps) - 0.185 + Xini;
         NoteSetHeidth = 0.073 + RowQuantity * 0.0055 + Yini;
         longstatus    = swAnn.SetLeader2(false, 0, true, true, false, false);
         boolstatus    = swAnn.SetPosition(NoteSetWidth, NoteSetHeidth, 0);
     }
     else
     {
     }
 }
Пример #11
0
        private void ReplaceViews(object[] swViews,DrawingDoc swDrawing)
        {
            Sheet currentSheet = swDrawing.GetCurrentSheet();
            double width = 0, height = 0;
            currentSheet.GetSize(ref width, ref height);
            double halfx = width / 2;
            double halfy = height / 2;
            Dictionary<string, double[]> boxes = new Dictionary<string, double[]>();
            foreach (View t in swViews)
            {
                var swView = (View)t;
                const string expr = "^F[1-6]$";
                Match isMatch = Regex.Match(swView.Name, expr, RegexOptions.IgnoreCase);
                if (!isMatch.Success)
                    continue;
                double[] bBox = swView.GetOutline();
                boxes.Add(swView.Name, bBox);
            }
            if (!boxes.ContainsKey("F1"))
            {
                return;
            }
            foreach (View t in swViews)
            {
                var swView = (View)t;

                if (swView.GetName2().Contains("F2"))
                {
                    swView.Position = new double[] { boxes["F1"][0]/2 , 0 };//{ boxes["F1"][0] - ((boxes["F1"][2] - boxes["F1"][0]) / 2), 0 };//{ boxes["F1"][0]/2, halfy - Math.Abs(deltay) };//{ boxes["F1"][0] - ((boxes["F1"][2] - boxes["F1"][0]) / 2), halfy - Math.Abs(deltay) };
                }
                if (swView.GetName2().Contains("F3"))
                {
                    swView.Position = new double[] { boxes["F1"][2] + ((width - boxes["F1"][2]) / 2), 0 };//{ boxes["F1"][2] + ((boxes["F1"][2] - boxes["F1"][0]) / 2), 0 };
                }
                if (swView.GetName2().Contains("F4"))
                {
                    swView.Position = new double[] { 0, boxes["F1"][3] + ((height - boxes["F1"][3]) / 2) };//{ 0, boxes["F1"][3] + ((boxes["F1"][3] - boxes["F1"][1]) / 2) };//{ halfx, boxes["F1"][3] + ((height - boxes["F1"][3]) / 2) - Math.Abs(deltay) };//{ halfx, boxes["F1"][3] + ((boxes["F1"][3] - boxes["F1"][1]) / 2) - Math.Abs(deltay) };
                }
                if (swView.GetName2().Contains("F5"))
                {
                    swView.Position = new double[] { 0, boxes["F1"][1]/ 2 };//{ 0, boxes["F1"][1] - ((boxes["F1"][3] - boxes["F1"][1]) / 2) };//{ halfx, boxes["F1"][1] - ((boxes["F1"][1]) / 2) - Math.Abs(deltay) };//{ halfx, boxes["F1"][1] - ((boxes["F1"][3] - boxes["F1"][1]) / 2) - Math.Abs(deltay) };
                }
            }
        }
        public void CmdRevMethod(bool m)
        {
            try
            {
                if (m & string.IsNullOrEmpty(TxtBox.Text))
                {
                    MessageBox.Show("Введите номер извещения.");
                    return;
                }

                for (var i = 0; i <= _vSheetNames.GetUpperBound(0); i++)
                {
                    //TODO: _swNote

                    //ok = _swDraw.ActivateSheet(_vSheetNames[i]);
                    _swDraw.ActivateSheet(_vSheetNames[i]);
                    _swSheet            = _swDraw.GetCurrentSheet();
                    _strSheetFormatName = _swSheet.GetSheetFormatName();

                    _swModel = (ModelDoc2)_swDraw;

                    _swSelMgr = _swModel.SelectionManager;

                    //MessageBox.Show(_swSelMgr.ToString());
                    // Дата
                    StrTempData = "Revision4@" + _strSheetFormatName;
                    ok          = _swModel.Extension.SelectByID2(StrTempData, "NOTE", 0, 0, 0, false, 0, null, 0);

                    if (ok)
                    {
                        _swNote = _swSelMgr.GetSelectedObject2(1);

                        //MessageBox.Show(_swNote.ToString());
                        if (m)
                        {
                            var date = (DateTime)StrData.SelectedDate;
                            StrTempData = Convert.ToString(date.ToString("dd-MM-yy"));
                            _swNote.SetText(StrTempData);
                        }
                        else
                        {
                            //MessageBox.Show(StrTempData);
                            StrTempData = _swNote.GetText();

                            if (StrTempData == "" | StrTempData == " ")
                            {
                                StrData.SelectedDate = (DateTime.Today);
                            }
                            else
                            {
                                StrData.SelectedDate = Convert.ToDateTime(StrTempData);
                            }
                        }
                    }

                    // Номер
                    StrTempNumber = "Revision3@" + _strSheetFormatName;
                    _swModel.Extension.SelectByID2(StrTempNumber, "NOTE", 0, 0, 0, false, 0, null, 0);

                    if (ok)
                    {
                        _swNote = _swSelMgr.GetSelectedObject2(1);

                        if (m)
                        {
                            StrTempNumber = "ИКД-" + TxtBox.Text;
                            _swNote.SetText(StrTempNumber);
                        }
                        else
                        {
                            StrTempNumber = _swNote.GetText();
                            if (StrTempNumber != " ")
                            {
                                TxtBox.Text = StrTempNumber.Substring(4);
                            }
                        }
                    }

                    // Зам.
                    _strTemp = "Revision2@" + _strSheetFormatName;
                    _swModel.Extension.SelectByID2(_strTemp, "NOTE", 0, 0, 0, false, 0, null, 0);


                    if (ok)
                    {
                        _swNote = _swSelMgr.GetSelectedObject2(1);


                        if (m)
                        {
                            if (Rb1.IsChecked == true)
                            {
                                _swNote.SetText("Зам.");
                                _swModel.DeleteCustomInfo2("", "Revision");
                            }

                            if (Rb3.IsChecked == true)
                            {
                                _swNote.SetText("Нов.");
                                _swModel.DeleteCustomInfo2("", "Revision");
                            }

                            if (Rb2.IsChecked == true)
                            {
                                _swNote.SetText("Змін.");
                                _swModel.DeleteCustomInfo2("", "Revision");
                                _swModel.AddCustomInfo3("", "Revision", 30, "");
                                _swModel.CustomInfo2["", "Revision"] = Convert.ToString(SpinButton.Content);
                            }
                        }
                        else
                        {
                            _strTemp = _swNote.GetText();

                            if (_strTemp == "Зам.")
                            {
                                Rb1.IsChecked        = true;
                                Rb3.IsChecked        = false;
                                Rb2.IsChecked        = false;
                                SpinButton.IsEnabled = false;
                            }

                            if (_strTemp == "Нов.")
                            {
                                Rb1.IsChecked        = false;
                                Rb3.IsChecked        = true;
                                Rb2.IsChecked        = false;
                                SpinButton.IsEnabled = false;
                            }

                            if (_strTemp == "Змін.")
                            {
                                Rb1.IsChecked        = false;
                                Rb3.IsChecked        = false;
                                Rb2.IsChecked        = true;
                                SpinButton.IsEnabled = true;
                            }

                            int  n;
                            bool isNumeric = int.TryParse(_swModel.CustomInfo2["", "Revision"], out n);

                            if (isNumeric)
                            {
                                SpinButton.Content = _swModel.CustomInfo2["", "Revision"];
                            }
                            else
                            {
                                _swModel.DeleteCustomInfo2("", "Revision");
                            }
                        }
                    }
                }

                // Возвращение активного листа
                _swDraw.ActivateSheet(_strActiveSheetName);

                // Перестраиваем чертеж
                _swModel.ForceRebuild3(false);

                _swModel.GraphicsRedraw2();
                _swModel.ClearSelection2(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "; " + ex.StackTrace);
            }
        }
Пример #13
0
        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;
            }
        }
Пример #14
0
        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);
            }
        }
Пример #15
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;
            }
        }
Пример #16
0
        void Start()
        {
            try
            {
                swApp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                swModel = swApp.ActiveDoc;

                RowQuantityMax = 25;
                newNoteName    = "TT";
                m1             = 0; // автонумерации включена;
                ListNumber     = 0;
                ListIndent     = 3;
                //ListFindent = -5;
                //ListMark = 0; // Списка нет
                ParaMark = 0; // Форматирования нет

                Xini = 0 / 1000;
                Yini = 0 / 1000;

                // Заполнение массива номеров
                Array.Resize(ref N, RowQuantityMax + 3);
                N[1] = "";
                N[2] = "->";
                for (i = 1; i <= RowQuantityMax; i++)
                {
                    N[i + 2] = Strings.LTrim(i.ToString() + ". ");
                }

                #region Чтение ТТ
                // Чтение ТТ
                CboTTType.Items.Clear();
                i = 0;

                // Заполняем ТТ в зависимости от выбранного языка
                foreach (var str in arrStrTT())
                {
                    TTFileString = str.ToString();
                    if (Strings.Left(TTFileString, 3) == "$$$")  // Проверка, является ли строка заголовком раздела
                    {
                        k = Strings.Len(TTFileString);
                        CboTTType.Items.Add(Strings.Right(TTFileString, k - 3));
                        i = i + 1;
                        j = 1;
                    }
                    else
                    {
                        TT[i, j] = TTFileString;
                        j        = j + 1;
                        Array.Resize(ref TTQuantity, i + 1);
                        TTQuantity[i] = j - 1;
                        //Debug.Print(TTQuantity[i].ToString());
                    }
                }

                //// Чтение файла ТТ
                //using (StreamReader SR = new StreamReader(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + @"\Source" + @"\TT.txt", Encoding.GetEncoding(1251)))
                //{
                //    while ((line = SR.ReadLine()) != null)
                //    {
                //    }
                //}

                CboTTType.SelectedIndex = 0;
                #endregion

                // Проверка формы
                RowQuantity = CboN.Count;
                while (RowQuantity > 1)
                {
                    CboUnLoad();
                    RowQuantity = CboN.Count;
                }

                // Заполнение первой строки
                CboN[0].Items.Clear();
                for (i = 1; i <= RowQuantityMax + 2; i++)
                {
                    CboN[0].Items.Add(N[i].ToString());
                }

                CboTT[0].Items.Clear();
                for (j = 1; j <= TTQuantity[1]; j++)
                {
                    CboTT[0].Items.Add(TT[1, j].ToString());
                }

                // Чтение заметки ТТ
                TTNote   = "";
                m2       = 0; // ТТ не прочитаны
                swSelMgr = swModel.SelectionManager;

                swDraw             = (DrawingDoc)swModel;
                swSheet            = swDraw.GetCurrentSheet();
                strActiveSheetName = swSheet.GetName();
                strTemp            = "TT@" + strActiveSheetName;
                //Debug.Print(strTemp);
                ok = swModel.Extension.SelectByID2(strTemp, "NOTE", 0, 0, 0, false, 0, null, 0);
                if (ok)
                {
                    swNote = swSelMgr.GetSelectedObject2(1);
                    TTNote = swNote.PropertyLinkedText;
                    m2     = 1; // ТТ прочитаны из заметки
                }

                #region Анализ прочитанной заметки
                // Анализ прочитанной заметки
                if (m2 == 1)
                {
                    TTNoteLength = Strings.Len(TTNote);

                    // Разбивка на строки
                    j = 1;
                    Array.Resize(ref TTNoteString, j + 1);
                    TTNoteString[j] = "";

                    for (k = 1; k < TTNoteLength; k++)
                    {
                        Symbol = Strings.Mid(TTNote, k, 1);
                        if (Symbol == Convert.ToString(Strings.Chr(10)))
                        {
                            j = j + 1;
                            Array.Resize(ref TTNoteString, j + 1);
                            TTNoteString[j] = "";
                        }
                        else if (Symbol == Convert.ToString(Strings.Chr(13)))
                        {
                        }
                        else
                        {
                            TTNoteString[j] = TTNoteString[j] + Symbol;
                        }
                    }
                    // Анализ строк
                    for (k = 1; k <= j; k++)
                    {
                        RowQuantity    = CboN.Count;
                        AnalyserString = TTNoteString[k];
                        Analyser1();
                        TTNoteString[k]    = AnalyserString;
                        TTNoteStringLength = Strings.Len(TTNoteString[k]);

                        if (ParaMark == 0)
                        {
                            if (ListNumber == 1)
                            {
                                CboN[RowQuantity - 1].SelectedIndex = 0; // Пусто
                                CboTT[RowQuantity - 1].Text         = TTNoteString[k];
                            }
                            else
                            {
                                CboN[RowQuantity - 1].SelectedIndex = 1; // Табуляция
                                CboTT[RowQuantity - 1].Text         = TTNoteString[k];
                            }
                        }
                        else
                        {
                            if (Strings.Left(TTNoteString[k], 1) == " ")       // Пробел в начале
                            {
                                if (Strings.Left(TTNoteString[k], 3) == "   ") // Три пробела в начале
                                {
                                    CboN[RowQuantity - 1].SelectedIndex = 1;   // Табуляция
                                    CboTT[RowQuantity - 1].Text         = Strings.Right(TTNoteString[k], TTNoteStringLength - 3);
                                }
                                else
                                {
                                    CboN[RowQuantity - 1].SelectedIndex = 0; // Пусто
                                    CboTT[RowQuantity - 1].Text         = TTNoteString[k];
                                }
                            }
                            else
                            {
                                if (Strings.Mid(TTNoteString[k], 2, 1) == ".") // Есть точка во втором знаке
                                {
                                    AnalyserString = Strings.Left(TTNoteString[k], 2) + " ";
                                    Analyser3();
                                    CboN[RowQuantity - 1].SelectedIndex = CboNListIndex;
                                    if (CboNListIndex == 0)
                                    {
                                        CboTT[RowQuantity - 1].Text = TTNoteString[k];
                                    }
                                    else
                                    {
                                        if (Strings.Mid(TTNoteString[k], 4, 1) == " ") // Есть пробел после точки
                                        {
                                            CboTT[RowQuantity - 1].Text = Strings.Right(TTNoteString[k], TTNoteStringLength - 3);
                                        }
                                        else // Нет пробела после точки
                                        {
                                            CboTT[RowQuantity - 1].Text = Strings.Right(TTNoteString[k], TTNoteStringLength - 2);
                                        }
                                    }
                                }
                                else // Нет точки в третьем знаке
                                {
                                    if (Strings.Mid(TTNoteString[k], 3, 1) == ".") // Есть точка в третьем знаке
                                    {
                                        AnalyserString = Strings.Left(TTNoteString[k], 3) + " ";
                                        Analyser3();
                                        CboN[RowQuantity - 1].SelectedIndex = CboNListIndex;
                                        if (CboNListIndex == 0)
                                        {
                                            CboTT[RowQuantity - 1].Text = TTNoteString[k];
                                        }
                                        else
                                        {
                                            if (Strings.Mid(TTNoteString[k], 4, 1) == " ") // Есть пробел после точки
                                            {
                                                CboTT[RowQuantity - 1].Text = Strings.Right(TTNoteString[k], TTNoteStringLength - 4);
                                            }
                                            else // Нет пробела после точки
                                            {
                                                CboTT[RowQuantity - 1].Text = Strings.Right(TTNoteString[k], TTNoteStringLength - 3);
                                            }
                                        }
                                    }
                                    else // Нет точки в третьем знаке
                                    {
                                        CboN[RowQuantity - 1].SelectedIndex = 0; // Пусто
                                        CboTT[RowQuantity - 1].Text         = TTNoteString[k];
                                    }
                                }
                            }
                        }
                        if (j - k != 0) // Проверка необходимости добавить строку
                        {
                            CboLoad();
                        }
                    }
                }
                else // Заметки не существует
                {
                    // Проверка свойства RowQuantity
                    if (swModel.CustomInfo["RowQuantity"] != "")
                    {
                        RowQuantitySet = Convert.ToInt32(swModel.CustomInfo["RowQuantity"]);
                    }
                    else
                    {
                        RowQuantitySet = 0;
                        k = 1;
                        // Определение числа строк, заполненных старой версией
                        while (k == 8)
                        {
                            TTName = "TT" + Strings.LTrim(k.ToString());
                            if (swModel.CustomInfo[TTName] == "")
                            {
                                break;
                            }
                            RowQuantitySet = RowQuantitySet + 1;
                            k = k + 1;
                        }
                    }
                    if (RowQuantitySet != 0)
                    {
                        m2 = 2;                               // ТТ прочитаны из свойств
                        for (k = 1; k <= RowQuantitySet; k++) // Чтение из свойств
                        {
                            NName          = "N" + Strings.LTrim(k.ToString());
                            TTName         = "TT" + Strings.LTrim(k.ToString());
                            AnalyserString = swModel.CustomInfo[TTName];
                            Analyser1();
                            TempString = AnalyserString;
                            if (ParaMark == 1)
                            {
                                if (ListNumber == 1)
                                {
                                    CboN[k - 1].SelectedIndex = 0; // Пусто
                                }
                                else
                                {
                                    CboN[k - 1].SelectedIndex = 1; // Табуляция
                                }
                            }
                            else
                            {
                                if (swModel.CustomInfo[NName] == "   ") // Три пробела в начале
                                {
                                    CboN[k - 1].SelectedIndex = 1;      // Табуляция
                                }
                                else
                                {
                                    AnalyserString = swModel.CustomInfo[NName];
                                    Analyser3();
                                    CboN[k - 1].SelectedIndex = CboNListIndex;
                                }
                            }

                            CboTT[k - 1].Text = TempString;
                            if (RowQuantitySet - k != 0)
                            {
                                CboLoad();
                            }
                        }
                    }
                }
                #endregion

                CmdAdd.Enabled   = false;
                CmdDel.Enabled   = false;
                CmdUp.Enabled    = false;
                CmdDown.Enabled  = false;
                CmdDiam.Enabled  = false;
                CmdDeg.Enabled   = false;
                CmdPM.Enabled    = false;
                ChkAlign.Checked = Convert.ToBoolean(1);

                RowQuantity     = CboN.Count;
                ChkList.Checked = ParaMark == 1 ? Convert.ToBoolean(1) : Convert.ToBoolean(0);

                if (m2 == 0) // Включение списка если ТТ не было
                {
                    ChkList.Checked = Convert.ToBoolean(1);
                }

                //TODO: ChkAutoN
                ChkAutoN.Checked = true;
                ChkAutoN_Click(true, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "; " + ex.StackTrace);
                Close();
            }
        }
Пример #17
0
        public void PreCalcNote(ModelDoc2 swDoc, String[] listt)
        {
            DrawingDoc swDraw       = (DrawingDoc)swDoc;
            TextFormat swTextFormat = null;

            // Находим и удаляем старые ТТ
            FindNDelOldNotes(swDoc);
            if (listt.Length == 0)
            {
                return;
            }

            // Создадим времменный блок. Туда будем вставлять строки и определять высоту блока.
            Note       swNoteTemp = (Note)swDoc.InsertNote("");
            Annotation myAnnot    = (Annotation)swNoteTemp.GetAnnotation();

            swTextFormat            = myAnnot.GetTextFormat(0) as TextFormat;
            swTextFormat.LineLength = c_width - 0.005;
            myAnnot.SetTextFormat(0, false, swTextFormat);
            swNoteTemp.SetTextJustification((int)swTextJustification_e.swTextJustificationLeft);

            // Определим доступное поле для ТТ
            Sheet swSheet = (Sheet)swDraw.GetCurrentSheet();

            swSheet.GetSize(ref sh_width, ref sh_height);
            double fheight = sh_height - c_topmargin - c_height - 1 * 0.005;

            notes.Add(new NoteTT());
            NoteTT ntt = notes[0];

            ntt.NoteText  = "<PARA indent=5 findent=-5 number=on ntype=1 nformat=$$. nstartNum = 1>";
            ntt.curheight = 0;

            const string notefmt = "<PARA indent=5 findent=-5 number=on ntype=1 nformat=$$.>";
            int          curind  = 0;

            for (int i = 0; i < listt.Length; i++)
            {
                ntt = notes[curind];
                string onestring = notefmt + listt[i];
                // Вставляем одну ТТ во временный блок
                swNoteTemp.SetText(onestring);
                double tempnoteheight = GetTempNoteHeight(swNoteTemp);
                // Проверяем получающуюся высоту примечания
                if (ntt.curheight + tempnoteheight <= fheight)
                {
                    // Если помещается, дописываем текст и увеличиваем высоту проверки
                    ntt.NoteText  += listt[i] + System.Environment.NewLine;
                    ntt.curheight += tempnoteheight;
                }
                else
                {
                    // Иначе создаём новое примечание
                    notes.Add(new NoteTT());
                    curind++;
                    ntt           = notes[curind];
                    ntt.NoteText  = "<PARA indent=5 findent=-5 number=on ntype=1 nformat=$$. nstartNum = " + (i + 1).ToString() + ">";
                    ntt.curheight = 0;
                }
            }

            swDoc.ClearSelection2(true);
            myAnnot.Select(false);
            swDoc.DeleteSelection(false);
            swDoc.WindowRedraw();
        }
Пример #18
0
        /// <summary>
        /// 出工程图
        /// </summary>
        /// <param name="dicValues"></param>
        /// <param name="prtTemp"></param>
        /// <param name="compTemp"></param>
        /// <param name="bomPaths"></param>
        /// <param name="savePaths">保存路径</param>
        /// <param name="newPath">新路径</param>
        private void Drawing(List <string> dicValues, string prtTemp, string compTemp, string bomPaths, string savePaths, string newPath)
        {
            string          viewType   = string.Empty;
            bool            isometric  = false;
            bool            bom        = false;
            string          dimesion   = string.Empty;
            double          spaceX     = 0.06;                  //x方向留白区域
            double          scale      = 1;                     //定义比例初始值
            List <double[]> viewBox    = new List <double[]>(); //集合存放视图box
            List <double[]> viewOrigin = new List <double[]>(); //集合存放视图原点值

            double[] outLine = new double[4];                   //视图box值
            double[] postion = new double[2];                   //视图原点值
            _swApp = (SldWorks)ConnectSW.iSwApp;                //连接sw
            if (_swApp == null)
            {
                return;
            }
            foreach (string item in dicValues)
            {
                int    errors   = 0;
                int    warnings = 0;
                double view1X   = 0;
                double view1Y   = 0;
                string filePath = item;                                             //文件路径
                string fileEx   = filePath.Substring(filePath.LastIndexOf("."), 7); //获得后缀名
                string filename = filePath.Substring(filePath.LastIndexOf("\\") + 1, filePath.LastIndexOf(".") - filePath.LastIndexOf("\\") - 1);
                if (fileEx == ".SLDPRT")
                {
                    _swModelDoc = (ModelDoc2)_swApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    __swDrawDoc = (DrawingDoc)_swApp.NewDrawing2((int)swDwgTemplates_e.swDwgTemplateCustom, prtTemp, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0);
                }
                if (fileEx == ".SLDASM")
                {
                    _swModelDoc = (ModelDoc2)_swApp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                    __swDrawDoc = (DrawingDoc)_swApp.NewDrawing2((int)swDwgTemplates_e.swDwgTemplateCustom, compTemp, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0);
                }
                _swModelEx = (ModelDocExtension)_swModelDoc.Extension;
                if (newPath != null)
                {
                    savePaths = newPath.Substring(0, newPath.LastIndexOf("\\"));
                }
                //新建工程图
                _swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAutomaticScaling3ViewDrawings, true); //自动缩放新工程图比例
                if (standarView == false && isometric)                                                               //如果只生成等轴测视图
                {
                    CreatIsometric(__swDrawDoc, filePath);
                    _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                    __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                    _swView = __swDrawDoc.GetFirstView();
                    _swView = _swView.GetNextView();
                    ChangeViewShow(tag, _swView);
                    _swApp.CloseDoc(_swModelDoc.GetTitle());//
                    ModelDoc2 tempDoc = (ModelDoc2)__swDrawDoc;
                    bool      ss0     = false;
                    if (newPath != null && IfDwg)
                    {
                        ss0 = tempDoc.Extension.SaveAs(newPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else if (newPath != null && IfDwg == false)
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else if (newPath == null && IfDwg)
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }
                    else
                    {
                        ss0 = tempDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf(".")) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                    }

                    bool isHidden = tempDoc.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swViewDisplayHideAllTypes, true); //隐藏所有类型
                    _swApp.CloseDoc(tempDoc.GetTitle());
                    _numSucess += 1;                                                                                                //转换成功的数量
                    sucessFile.Add(filePath);
                    return;
                }
                bool isCreate = false;
                #region 第三视角投影
                if (thirProject)
                {
                    isCreate = __swDrawDoc.Create3rdAngleViews2(filePath);//创建第三视角投影视图(视图位置有差别)
                    //调整视图位置
                    _swView = __swDrawDoc.GetFirstView();
                    while (_swView != null)
                    {
                        double[] vBox   = new double[] { };
                        double[] vPoint = new double[] { };
                        vBox   = (double[])_swView.GetOutline();
                        vPoint = (double[])_swView.Position;
                        viewBox.Add(vBox);
                        viewOrigin.Add(vPoint);
                        _swView = _swView.GetNextView();
                    }
                    //调整视图1、2位置
                    if (viewBox[0][3] > viewBox[0][2])//纵向
                    {
                        double[] posView1 = new double[] { viewBox[0][2] / 3.0, viewOrigin[1][1] };
                        _swView          = __swDrawDoc.GetFirstView();
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView1;
                        double[] posView2 = new double[] { viewOrigin[2][0], viewOrigin[2][1] - (viewBox[2][1] - viewBox[1][3]) / 1.9 };//调整视图2位置
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView2;
                    }
                    else
                    {
                        double[] posView1 = new double[] { viewBox[0][2] / 4.0, viewOrigin[1][1] };
                        _swView          = __swDrawDoc.GetFirstView();
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView1;
                        double[] posView2 = new double[] { viewOrigin[2][0], viewOrigin[2][1] - (viewBox[2][1] - viewBox[1][3]) / 2.0 };//调整视图2位置
                        _swView          = _swView.GetNextView();
                        _swView.Position = posView2;
                    }
                    viewOrigin.Clear();
                    viewBox.Clear();
                    _swView = __swDrawDoc.GetFirstView();
                    while (_swView != null)
                    {
                        double[] vBox   = new double[] { };
                        double[] vPoint = new double[] { };
                        vBox   = (double[])_swView.GetOutline();
                        vPoint = (double[])_swView.Position;
                        viewBox.Add(vBox);
                        viewOrigin.Add(vPoint);
                        _swView = _swView.GetNextView();
                    }
                    if (isometric)//等轴测
                    {
                        _swView = (IView)__swDrawDoc.CreateDrawViewFromModelView3(filePath, "*等轴测", viewOrigin[3][0], viewOrigin[2][1], 0);
                        _swView = __swDrawDoc.GetFirstView();
                        double[] sca = new double[2];
                        sca                = _swView.ScaleRatio;//获取比例
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView.ScaleRatio = sca;
                        double[] rePos = new double[] { viewOrigin[3][0] + 0.015, viewOrigin[2][1] };
                        _swView.Position = rePos;
                        ChangeViewShow(tag, _swView);                     //视图样式
                        AddDimension(dimesion, __swDrawDoc, _swModelDoc); //尺寸标注
                    }
                }
                #endregion
                #region 第一视角投影
                else
                {
                    isCreate = __swDrawDoc.Create1stAngleViews(filePath);//创建第一视角投影视图
                    //获取视图boundingbox
                    _swView = __swDrawDoc.GetFirstView();
                    while ((_swView != null))
                    {
                        outLine = (double[])_swView.GetOutline(); //(x,y坐标最值)
                        postion = (double[])_swView.Position;     //视图位置值
                        viewBox.Add(outLine);
                        viewOrigin.Add(postion);
                        _swView = _swView.GetNextView();
                    }

                    double newScale = CalcuScale(viewBox, __swDrawDoc, scale, spaceX, 3);
                    //调整视图位置(position)
                    if (viewBox[0][3] > viewBox[0][2])
                    {
                        view1X = viewBox[0][2] / 2.8;                  //视图1的X坐标放在图纸坐标的三分之一处
                        view1Y = viewBox[0][3] - viewBox[0][3] / 4.85; //视图1的Y坐标放在图纸坐标的五分之一处
                    }
                    else
                    {
                        view1X = viewBox[0][2] / 3.5;                 //视图1的X坐标放在图纸坐标的三分之一处
                        view1Y = viewBox[0][3] - viewBox[0][3] / 4.0; //视图1的Y坐标放在图纸坐标的四分之一处
                    }
                    double[] view1Pos = new double[] { view1X, view1Y };
                    _swView          = __swDrawDoc.GetFirstView(); //获取图纸
                    _swView          = _swView.GetNextView();      //获取第一个视图
                    _swView.Position = view1Pos;
                    bool isRebuild = _swModelDoc.EditRebuild3();
                    //viewBox.Clear();
                    List <double[]> tempBox = new List <double[]>();
                    viewOrigin.Clear();
                    while ((_swView != null))
                    {
                        ChangeViewShow(tag, _swView);                     //改变视图显示样式
                        AddDimension(dimesion, __swDrawDoc, _swModelDoc); //添加尺寸
                        outLine = (double[])_swView.GetOutline();         //(x,y坐标最值)
                        postion = (double[])_swView.Position;             //视图位置值
                        tempBox.Add(outLine);
                        viewOrigin.Add(postion);
                        _swView = _swView.GetNextView();
                    }
                    if (isometric)  //是否创建等轴测视图(非钣金)
                    {
                        double[] scalArry = new double[2];
                        _swView = (IView)__swDrawDoc.CreateDrawViewFromModelView3(filePath, "*等轴测", viewOrigin[2][0], viewOrigin[1][1], 0);
                        _swView = __swDrawDoc.GetFirstView(); //获取图纸
                        _swView = _swView.GetNextView();      //获取第一个视图
                        double sca = _swView.get_IScaleRatio();
                        if (sca == 1)                         //缩小比例
                        {
                            scalArry[0] = 1;
                            scalArry[1] = newScale;
                        }
                        else
                        {
                            scalArry[0] = sca;
                            scalArry[1] = 1;
                        }
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView            = _swView.GetNextView();
                        _swView.ScaleRatio = scalArry;//调整轴测图比例
                        ChangeViewShow(tag, _swView);
                        _swModelDoc.EditRebuild3();
                    }
                    ////关掉文件(不保存)
                    //_swApp.CloseDoc(_swModelDoc.GetTitle());
                    if (fileEx == ".SLDASM" && bom)        //是否创建明细表
                    {
                        //viewBox.Clear();
                        //viewOrigin.Clear();
                        double[] outArry  = new double[4];
                        double[] posArry  = new double[2];
                        double[] posArry1 = null;
                        double[] posArry2 = null;
                        double[] posArry3 = null;
                        _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                        __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                        _swView        = __swDrawDoc.GetFirstView(); //获取图纸
                        _swView        = _swView.GetNextView();      //获取第一个视图
                        swBomTableAnno = (BomTableAnnotation)_swView.InsertBomTable4(true, 0.4, 0.1, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_BottomRight, (int)swBomType_e.swBomType_TopLevelOnly, "", bomPaths, false, 0, false);
                        TableAnnotation tableAnnotation = (TableAnnotation)swBomTableAnno;
                        tableAnnotation.GetAnnotation();
                        BomFeature bomFeature     = swBomTableAnno.BomFeature;
                        bool[]     array          = new bool[bomFeature.GetConfigurationCount(false)];
                        object     Visible        = array;
                        object     configurations = bomFeature.GetConfigurations(false, ref Visible);
                        array[0] = true;
                        bomFeature.SetConfigurations(true, array, configurations);
                        FeatureManager featureManager = _swModelDoc.FeatureManager;
                        featureManager.UpdateFeatureTree();
                        double num = 0.007;
                        tableAnnotation.SetRowHeight(-2, num, 0);
                        double totleHeight = num * tableAnnotation.RowCount; //计算总的tableBom高度
                        double heightSum   = totleHeight + 0.070;            //加上标题栏总高度
                        int    columCount  = tableAnnotation.ColumnCount;    //获取总的列数
                        double columWidth  = 0;
                        for (int i = 0; i < columCount; i++)
                        {
                            double wid = tableAnnotation.GetColumnWidth(i);
                            columWidth += wid;
                        }
                        _swView = _swView.GetNextView();
                        _swView = _swView.GetNextView();
                        outArry = (double[])_swView.GetOutline();
                        if (outArry[1] < heightSum)//有可能被遮挡
                        {
                            //__swView = _swDrawDoc.GetFirstView();
                            //double[] tempArry = new double[] { };
                            //tempArry=(double[])__swView.GetOutline();
                            //viewBox.Insert(0, tempArry);
                            scale = ((viewBox[1][2] - viewBox[1][0]) + (viewBox[3][2] - viewBox[3][0])) / (viewBox[0][2] - columWidth - 0.025);//计算X方向的比例
                            if (scale > 11)
                            {
                                double scaleCeil = System.Math.Ceiling(scale);
                                if (scaleCeil > 11 && scaleCeil < 16)
                                {
                                    scale = 20;
                                }
                                if (scaleCeil > 15 && scaleCeil < 21)
                                {
                                    scale = 25;
                                }
                                if (scaleCeil > 20 && scaleCeil < 26)
                                {
                                    scale = 30;
                                }
                                if (scaleCeil > 25 && scaleCeil < 34)
                                {
                                    scale = 40;
                                }
                                if (scaleCeil > 33 && scaleCeil < 45)
                                {
                                    scale = 50;
                                }
                                if (scaleCeil > 44 && scaleCeil < 55)
                                {
                                    scale = 60;
                                }
                            }
                            else if (scale > 5.8 && scale < 10.5)
                            {
                                double scaleCeil = System.Math.Ceiling(scale);
                                //scale = scaleCeil + 4.0;          //比例为10、11、12、13、14、15
                                if (scaleCeil > 5 && scaleCeil < 8)
                                {
                                    scale = 10;
                                }
                                if (scaleCeil > 7 && scaleCeil < 12)
                                {
                                    scale = 15;
                                }
                            }
                            _currentSheet = (Sheet)__swDrawDoc.GetCurrentSheet();
                            __swDrawDoc.ActivateSheet(_currentSheet.GetName());
                            bool isScale = _currentSheet.SetScale(1, scale, false, false); //设置视图和图纸比例
                            _swView = __swDrawDoc.GetFirstView();
                            _swView = _swView.GetNextView();                               //获取视图1
                            double[] pos1 = new double[2];
                            pos1             = _swView.Position;
                            posArry1         = new double[] { pos1[0] - columWidth / 3.45, pos1[1] };
                            _swView.Position = posArry1;              //重置视图1的位置
                            _swView          = _swView.GetNextView(); //获取视图2
                            double[] pos2 = new double[2];
                            pos2             = _swView.Position;
                            posArry2         = new double[] { pos2[0] - columWidth / 3.45, pos2[1] + 0.0015 };
                            _swView.Position = posArry2;              //设置视图2位置
                            _swView          = _swView.GetNextView(); //获取视图三
                            posArry          = (double[])_swView.Position;
                            posArry3         = new double[] { posArry[0] - columWidth / 3.5, posArry[1] };
                            _swView.Position = posArry3;//视图3坐标
                        }
                    }
                }//第一视角投影
                #endregion
                if (isCreate)
                {
                    _numSucess += 1;//转换成功的数量
                    sucessFile.Add(filePath);
                }
                ModelDoc2 tempModelDoc = (ModelDoc2)__swDrawDoc;                                                                    //获取到swDraw的父级(ModelDoc)
                _swApp.CloseDoc(_swModelDoc.GetTitle());
                bool isHiden = tempModelDoc.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swViewDisplayHideAllTypes, true); //隐藏所有类型

                _swModelDoc.ForceRebuild3(false);
                string saveName = (_swModelDoc.GetTitle()).Substring(0, (_swModelDoc.GetTitle()).LastIndexOf("."));
                bool   ss;
                if (newPath != null && IfDwg)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else if (newPath != null && IfDwg == false)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else if (newPath == null && IfDwg)
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".DWG", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                else
                {
                    ss = tempModelDoc.Extension.SaveAs(savePaths + "\\" + (_swModelDoc.GetTitle()) + ".slddrw", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
                }
                _swApp.CloseDoc(tempModelDoc.GetTitle());//关闭转换完成的文件
            }
        }
Пример #19
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
            }
        }
Пример #20
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);
        }
Пример #21
0
        /// <summary>
        /// 计算修改比列
        /// </summary>
        /// <param name="box"></param>
        /// <param name="swDraw"></param>
        /// <param name="scale"></param>
        /// <param name="space"></param>
        private double CalcuScale(List <double[]> box, DrawingDoc swDraw, double scale, double space, int viewNum)
        {
            if (box[0][3] > box[0][2] && viewNum == 3)                                                    //(纵向)三个视图
            {
                scale = ((box[1][2] - box[1][0]) + (box[3][2] - box[3][0])) / (box[0][2] - space - 0.01); //计算X方向的比例
            }
            else if (box[0][3] < box[0][2] && viewNum == 3)                                               //(横向)
            {
                scale = ((box[1][3] - box[1][1]) + (box[2][3] - box[2][1])) / (box[0][3] - space - 0.01); //计算Y方向的比例
            }
            else if (box[0][3] > box[0][2] && viewNum == 2)                                               //两个视图(钣金展开用:等轴测+展开图)
            {
                scale = (box[2][2] - box[2][0]) / (box[0][2] - space - 0.01);                             //计算X方向的比例
            }
            else if (box[0][3] < box[0][2] && viewNum == 2)                                               //两个视图(钣金展开用)
            {
                scale = (box[2][3] - box[2][1]) / (box[0][3] - space - 0.01);                             //计算Y方向的比例
            }
            else if (box[0][3] > box[0][2] && viewNum == 1)                                               //(只有等轴测)
            {
                scale = (box[1][2] - box[1][0]) / (box[0][2] - space - 0.01);                             //计算X方向的比例
            }
            else if (box[0][3] < box[0][2] && viewNum == 1)                                               //(只有等轴测)
            {
                scale = (box[1][3] - box[1][1]) / (box[0][3] - space - 0.01);                             //计算Y方向的比例
            }

            if (!stardardScale)
            {
                if (scale > 1.0)
                {
                    if (scale > 11)
                    {
                        double scaleCeil = System.Math.Ceiling(scale);
                        scale = scaleCeil + 6.0;//比例为18+
                    }
                    else if (scale > 5.8 && scale < 10.5)
                    {
                        double scaleCeil = System.Math.Ceiling(scale);
                        scale = scaleCeil + 5;          //比例为10、11、12、13、14、15
                    }
                    else
                    {
                        if (scale > 3.84 && scale < 5.85)
                        {
                            double scaleCeil = System.Math.Ceiling(scale);
                            scale = scaleCeil + 3.0;//比例为7、8、9
                        }
                        if (scale > 2.84 && scale < 3.85)
                        {
                            double scaleCeil = System.Math.Ceiling(scale);
                            scale = scaleCeil + 2.0;//比例为5或6
                        }
                        if (scale > 1.35 && scale < 2.85)
                        {
                            double scaleCeil = System.Math.Ceiling(scale);
                            scale = scaleCeil + 1.0;//比例为3或4
                        }
                        if (scale > 1 && scale < 1.36)
                        {
                            double scaleCeil = System.Math.Ceiling(scale);
                            scale = scaleCeil;//比例为2
                        }
                    }
                    _currentSheet = (Sheet)swDraw.GetCurrentSheet();
                    swDraw.ActivateSheet(_currentSheet.GetName());
                    bool isScale = _currentSheet.SetScale(1, scale, false, false);//设置视图和图纸比例
                }
                else if (scale > 0.7 && scale < 1.0)
                {
                    double scaleCeil2 = System.Math.Ceiling(scale);
                    scale         = scaleCeil2 + 1.0;
                    _currentSheet = (Sheet)swDraw.GetCurrentSheet();
                    swDraw.ActivateSheet(_currentSheet.GetName());
                    bool isScale = _currentSheet.SetScale(1, scale, false, false);//设置视图和图纸比例
                }
                else//scale<1.0
                {
                    double scaleRound = System.Math.Round(scale, 3);//小数的四舍五入
                    if (scaleRound > 0.12 && scaleRound < 0.130)
                    {
                        scale = 50;
                    }
                    if (scaleRound > 0.130 && scaleRound < 0.138)
                    {
                        scale = 40;
                    }
                    if (scaleRound > 0.138 && scaleRound < 0.151)
                    {
                        scale = 20;
                    }
                    if (scaleRound > 0.151 && scaleRound < 0.178)
                    {
                        scale = 10;
                    }
                    if (scaleRound > 0.178 && scaleRound < 0.195)
                    {
                        scale = 6;
                    }
                    if (scaleRound > 0.195 && scaleRound < 0.230)
                    {
                        scale = 5;
                    }
                    if (scaleRound > 0.229 && scaleRound < 0.280)
                    {
                        scale = 4;
                    }
                    if (scaleRound > 0.279 && scaleRound < 0.305)
                    {
                        scale = 3;
                    }
                    if (scaleRound > 0.304 && scaleRound < 0.350)
                    {
                        scale = 2.5;
                    }
                    if (scaleRound > 0.349 && scaleRound < 0.405)
                    {
                        scale = 2;
                    }
                    if (scaleRound > 0.405 && scaleRound < 0.71)
                    {
                        scale = 1;
                    }
                    _currentSheet = (Sheet)swDraw.GetCurrentSheet();
                    swDraw.ActivateSheet(_currentSheet.GetName());
                    bool isScales = _currentSheet.SetScale(scale, 1, false, false);//设置视图和图纸比例
                }
            }
            if (stardardScale)//国标比例
            {
                if (scale > 1.0)
                {
                    if (scale > 11)
                    {
                        double scaleCeil = System.Math.Ceiling(scale);
                        if (scaleCeil > 11 && scaleCeil < 16)
                        {
                            scale = 20;
                        }
                        if (scaleCeil > 15 && scaleCeil < 21)
                        {
                            scale = 25;
                        }
                        if (scaleCeil > 20 && scaleCeil < 26)
                        {
                            scale = 30;
                        }
                        if (scaleCeil > 25 && scaleCeil < 34)
                        {
                            scale = 40;
                        }
                        if (scaleCeil > 33 && scaleCeil < 45)
                        {
                            scale = 50;
                        }
                        if (scaleCeil > 44 && scaleCeil < 55)
                        {
                            scale = 60;
                        }
                    }
                    else if (scale > 5.8 && scale < 10.5)
                    {
                        double scaleCeil = System.Math.Ceiling(scale);
                        //scale = scaleCeil + 4.0;          //比例为10、11、12、13、14、15
                        if (scaleCeil > 5 && scaleCeil < 8)
                        {
                            scale = 10;
                        }
                        if (scaleCeil > 7 && scaleCeil < 12)
                        {
                            scale = 15;
                        }
                    }
                    else
                    {
                        if (scale > 3.84 && scale < 5.85)
                        {
                            double scaleCeil = System.Math.Ceiling(scale);
                            //scale = scaleCeil + 3.0;//比例为7、8、9
                            if (scaleCeil == 4)
                            {
                                scale = 6;
                            }
                            if (scaleCeil > 4 && scaleCeil < 7)
                            {
                                scale = 10;
                            }
                        }
                        if (scale > 2.84 && scale < 3.85)
                        {
                            double scaleCeil = System.Math.Ceiling(scale);
                            scale = scaleCeil + 2.0;//比例为5或6
                        }
                        if (scale > 1.35 && scale < 2.85)
                        {
                            double scaleCeil = System.Math.Ceiling(scale);
                            scale = scaleCeil + 1.0;//比例为3或4
                        }
                        if (scale > 1 && scale < 1.36)
                        {
                            double scaleCeil = System.Math.Ceiling(scale);
                            scale = scaleCeil;//比例为2
                        }
                    }
                    _currentSheet = (Sheet)swDraw.GetCurrentSheet();
                    swDraw.ActivateSheet(_currentSheet.GetName());
                    bool isScale = _currentSheet.SetScale(1, scale, false, false);//设置视图和图纸比例
                }
                else if (scale > 0.7 && scale < 1.0)
                {
                    double scaleCeil2 = System.Math.Ceiling(scale);
                    scale         = scaleCeil2 + 1.0;//比例为2
                    _currentSheet = (Sheet)swDraw.GetCurrentSheet();
                    swDraw.ActivateSheet(_currentSheet.GetName());
                    bool isScale = _currentSheet.SetScale(1, scale, false, false);
                }
                else//scale<1.0
                {
                    double scaleRound = System.Math.Round(scale, 3);//小数的四舍五入
                    if (scaleRound > 0.12 && scaleRound < 0.130)
                    {
                        scale = 50;
                    }
                    if (scaleRound > 0.130 && scaleRound < 0.138)
                    {
                        scale = 40;
                    }
                    if (scaleRound > 0.138 && scaleRound < 0.151)
                    {
                        scale = 20;
                    }
                    if (scaleRound > 0.151 && scaleRound < 0.178)
                    {
                        scale = 10;
                    }
                    if (scaleRound > 0.178 && scaleRound < 0.195)
                    {
                        scale = 6;
                    }
                    if (scaleRound > 0.195 && scaleRound < 0.255)
                    {
                        scale = 5;
                    }
                    if (scaleRound > 0.255 && scaleRound < 0.285)
                    {
                        scale = 4;
                    }
                    if (scaleRound > 0.285 && scaleRound < 0.308)
                    {
                        scale = 3;
                    }
                    if (scaleRound > 0.307 && scaleRound < 0.340)
                    {
                        scale = 2.5;
                    }
                    if (scaleRound > 0.339 && scaleRound < 0.405)
                    {
                        scale = 2;
                    }
                    if (scaleRound > 0.405 && scaleRound < 0.71)
                    {
                        scale = 1;
                    }
                    _currentSheet = (Sheet)swDraw.GetCurrentSheet();
                    swDraw.ActivateSheet(_currentSheet.GetName());
                    bool isScales = _currentSheet.SetScale(scale, 1, false, false);//设置视图和图纸比例
                }
            }
            return(scale);
        }
Пример #22
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;
            }
        }