Beispiel #1
0
        /// <summary>
        /// Pull the description string from a part/assembly in a View.
        /// </summary>
        /// <param name="v">A View object.</param>
        /// <returns>A description string.</returns>
        public static string get_description(SolidWorks.Interop.sldworks.View v)
        {
            ModelDoc2            md    = (ModelDoc2)v.ReferencedDocument;
            ConfigurationManager cfMgr = md.ConfigurationManager;
            Configuration        cf    = cfMgr.ActiveConfiguration;

            CustomPropertyManager gcpm = md.Extension.get_CustomPropertyManager(string.Empty);
            CustomPropertyManager scpm;

            string _value    = "PART";
            string _resValue = string.Empty;
            bool   wasResolved;
            bool   useCached = false;

            if (cf != null)
            {
                scpm = cf.CustomPropertyManager;
            }
            else
            {
                scpm = gcpm;
            }
            int res;

            res = gcpm.Get5("Description", useCached, out _value, out _resValue, out wasResolved);
            if (_value == string.Empty)
            {
                res = scpm.Get5("Description", useCached, out _value, out _resValue, out wasResolved);
            }
            return(_value);
        }
Beispiel #2
0
        public void hidebomtable()
        {
            SldWorks   swApp   = default(SldWorks);
            ModelDoc2  swModel = default(ModelDoc2);
            DrawingDoc swDraw  = default(DrawingDoc);

            SolidWorks.Interop.sldworks.View swView = default(SolidWorks.Interop.sldworks.View);
            TableAnnotation swTableAnn = default(TableAnnotation);
            Annotation      swAnn      = default(Annotation);

            object[] vTableAnns = null;
            int      i          = 0;

            //swApp = CreateObject("SldWorks.Application")
            swApp      = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            swModel    = swApp.ActiveDoc;
            swDraw     = (DrawingDoc)swModel;
            swView     = swDraw.GetFirstView();
            vTableAnns = swView.GetTableAnnotations();
            //vTableAnns.Length
            if ((vTableAnns == null) == false)
            {
                for (i = 0; i <= vTableAnns.Length - 1; i++)
                {
                    swTableAnn = (TableAnnotation)vTableAnns[i];
                    if (swTableAnn.Type == (int)swTableAnnotationType_e.swTableAnnotation_BillOfMaterials)
                    {
                        //swTableAnn.MoveColumn(0, swTableItemInsertPosition_e.swTableItemInsertPosition_After, 1)
                        swAnn = swTableAnn.GetAnnotation();
                        swAnn.Select3(false, null);
                        swApp.RunCommand((int)swCommands_e.swCommands_Hide_Table, null);
                    }
                }
            }
        }
Beispiel #3
0
        public static void InsertBOM(SldWorks swApp)
        {
            ModelDoc2         md = (ModelDoc2)swApp.ActiveDoc;
            DrawingDoc        dd = (DrawingDoc)swApp.ActiveDoc;
            ModelDocExtension ex = (ModelDocExtension)md.Extension;
            int bom_type         = (int)swBomType_e.swBomType_PartsOnly;
            int bom_numbering    = (int)swNumberingType_e.swNumberingType_Flat;
            int bom_anchor       = (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft;

            SolidWorks.Interop.sldworks.View v = GetFirstView(swApp);
            BomTableAnnotation bta             = null;
            TableAnnotation    ta = null;

            if (dd.ActivateView(v.Name))
            {
                bta = v.InsertBomTable4(
                    false,
                    Properties.Settings.Default.BOMLocationX, Properties.Settings.Default.BOMLocationY,
                    bom_anchor,
                    bom_type,
                    v.ReferencedConfiguration,
                    Properties.Settings.Default.BOMTemplatePath,
                    false,
                    bom_numbering,
                    false);
            }

            if (bta != null)
            {
                ta = (TableAnnotation)bta;
                if (ta != null)
                {
                    int        deptcol = 0;
                    List <int> rowdpt  = new List <int>();
                    System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(BOMFilter[0]);

                    for (int i = 0; i < ta.ColumnCount; i++)
                    {
                        if (ta.Text[0, i].ToUpper() == @"DEPTID")
                        {
                            deptcol = i;
                            break;
                        }
                    }

                    for (int i = 0; i < ta.RowCount; i++)
                    {
                        if (!r.IsMatch(ta.Text[i, deptcol]))
                        {
                            rowdpt.Add(i);
                        }
                    }

                    foreach (int item in rowdpt)
                    {
                        ta.set_RowHidden(item, true);
                    }
                }
            }
        }
Beispiel #4
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);
        }
Beispiel #5
0
        //第一步,先得到一个视图下所有要重新排序的Note,这里一个视图一组,
        //返回HashTable,Note---Point
        private Hashtable GetAllNote(ModelDoc2 swModel, SolidWorks.Interop.sldworks.View swView, bool OnlySelected)
        {
            Hashtable htRet = new Hashtable();

            //if (OnlySelected)//只选择选中的
            //{
            //    SelectionMgr SelMgr = (SelectionMgr)swModel.SelectionManager;
            //    int Count = SelMgr.GetSelectedObjectCount2(0);//选中的个数
            //    for (int i = 1; i <= Count; i++)
            //    {
            //        try
            //        {
            //            object o = SelMgr.GetSelectedObject6(i, 0);//0:忽略当前的,-1:忽略全部
            //            Note not = (Note)o;
            //            double[] dbArr = (double[])not.GetTextPoint2();

            //            htRet.Add(not, dbArr);
            //        }
            //        catch
            //        { }
            //    }
            //}
            //else//所有的////////////////////////////////////////////////////////////////////////////
            //{
            //    //遍历注释
            //    Note not = (Note)swView.GetFirstNote();
            //    while (not != null)
            //    {
            //        string txt = not.GetText();
            //        try
            //        {
            //            int a = Convert.ToInt32(txt);
            //            //如果不是数字,这一步会结束
            //            Annotation ann = (Annotation)not.GetAnnotation();
            //            object[] obArr = (object[])ann.GetAttachedEntities2();
            //            object oc = obArr[0];
            //            Entity ent = (Entity)oc;
            //            Component2 comp = (Component2)ent.GetComponent();

            //            //添加到哈希表
            //            htRet.Add(not, (double[])not.GetTextPoint2());
            //        }
            //        catch
            //        { }
            //        not = (Note)not.GetNext();
            //    }
            //}
            return(htRet);
        }
Beispiel #6
0
        private void TraverseFile(DirectoryInfo dir, string OldName, string NewName)
        {
            foreach (FileInfo fi in dir.GetFiles())
            {
                if (fi.Extension.ToLower() != ".drwdot" && fi.Extension.ToLower() != ".slddrw")
                {
                    continue;                                                                            //slddrt.
                }
                string    str     = fi.FullName;
                ModelDoc2 swModel = (ModelDoc2)AllData.iSwApp.OpenDoc(str, (int)swDocumentTypes_e.swDocDRAWING);
                if (swModel == null)
                {
                    iErr++; continue;
                }
                DrawingDoc swDraw = (DrawingDoc)swModel;
                if (swDraw == null)
                {
                    iErr++; continue;
                }

                swDraw.EditTemplate();

                SolidWorks.Interop.sldworks.View swView = (SolidWorks.Interop.sldworks.View)swDraw.GetFirstView();
                Note swnote = (Note)swView.GetFirstNote();
                while (swnote != null)
                {
                    string s = swnote.GetText().ToString();
                    if (s == OldName)
                    {
                        swnote.SetText(NewName);
                        iOK++;
                        //这里需要保存
                        swDraw.EditSheet();
                        swModel.Save();
                    }
                    swnote = (Note)swnote.GetNext();
                }
                AllData.iSwApp.CloseDoc(swModel.GetTitle());
            }

            foreach (DirectoryInfo dirsub in dir.GetDirectories())
            {
                TraverseFile(dirsub, OldName, NewName);
            }
        }
Beispiel #7
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;
            }
        }
Beispiel #8
0
        //得到线的三点,和比例//对一个视图的数据初始化
        private void GetViewThreePointAndScale(SolidWorks.Interop.sldworks.View swView)
        {
            double[] dbViewArr = (double[])swView.GetOutline();    //得到两个点坐标:左下角,右上角

            this.dbArrLine[0] = dbViewArr[0];                      //左上角
            this.dbArrLine[1] = dbViewArr[3];
            this.dbArrLine[2] = dbViewArr[2];                      //右下角
            this.dbArrLine[3] = dbViewArr[1];
            this.dbArrLine[4] = (dbViewArr[0] + dbViewArr[2]) / 2; //中心点
            this.dbArrLine[5] = (dbViewArr[3] + dbViewArr[1]) / 2;

            //X长度//中心点到左上角
            double x0 = this.dbArrLine[4] - this.dbArrLine[0];
            double y0 = this.dbArrLine[5] - this.dbArrLine[1];

            //左上角到中心点的距离,用来计算角度//三边计算角度
            this.distAC = Math.Sqrt(x0 * x0 + y0 * y0);

            this.scale = x0 / y0;//比例关系
        }
Beispiel #9
0
        private IEnumerable<Feature> HideUnusedComponents(View swView, bool dimOnlyNew)
        {
            var features = new List<Feature>();

            try
            {
                var comp = swView.RootDrawingComponent;
                if (comp.GetChildrenCount() == 0)
                {
                    if (dimOnlyNew)
                    {
                        var rootComp = _swAdd.RootModel.IGetActiveConfiguration().IGetRootComponent2();
                        if (rootComp != null)
                        {
                            var outComponents = new LinkedList<Component2>();
                            if (_swAdd.GetComponents(rootComp, outComponents, true, false))
                            {
                                Component2 neededComp = (from outComponent in outComponents
                                                         let mod = outComponent.IGetModelDoc()
                                                         where mod != null
                                                         let name = Path.GetFileNameWithoutExtension(mod.GetPathName())
                                                         let drName = comp.Name.Substring(0, comp.Name.LastIndexOf('-'))
                                                         where name == drName
                                                         select outComponent).FirstOrDefault();

                                if (neededComp != null)
                                {
                                    var mod = neededComp.IGetModelDoc();
                                    var fm = mod.FeatureManager;
                                    var oswFeat = (object[])fm.GetFeatures(true);
                                    foreach (var ofeature in oswFeat)
                                    {
                                        var feature = (Feature)ofeature;
                                        string name = feature.GetTypeName2();
                                        if (name == "ICE" || name == "HoleWzd")
                                        {
                                            if (!feature.IsSuppressed())
                                            {
                                                feature.SetSuppression(0);
                                                features.Add(feature);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                    foreach (var oSwComp in (object[])comp.GetChildren())
                    {
                        var swComp = (DrawingComponent) oSwComp;
                        if (swComp.Visible)
                        {
                            var mod = swComp.Component.IGetModelDoc();

                            if (mod != null)
                            {

                                    if (dimOnlyNew)
                                    {
                                        var fm = mod.FeatureManager;
                                        var oswFeat = (object[]) fm.GetFeatures(true);
                                        foreach (var ofeature in oswFeat)
                                        {
                                            var feature = (Feature) ofeature;
                                            string name1 = feature.GetTypeName2();
                                            if (name1 == "ICE" || name1 == "HoleWzd")
                                            {
                                                if (!feature.IsSuppressed())
                                                {
                                                    feature.SetSuppression(0);
                                                    features.Add(feature);
                                                }
                                            }
                                        }
                                    }
                                if (mod.CustomInfo2["", "Accessories"] == "Yes" || mod.CustomInfo2["","HideOnDraft"]=="Yes")
                                    swComp.Visible = false;
                            }
                        }
                    }
            }
            catch { }

            return features;
        }
Beispiel #10
0
 public SizeForDim(double xLeft, double yUp, double xRight, double yDown, double x, double y, double[] bound, View view)
 {
     XLeft = xLeft;
     YUp = yUp;
     XRight = xRight;
     YDown = yDown;
     X = x;
     Y = y;
     Bound = bound;
     View = view;
 }
Beispiel #11
0
        public Ordinate GetVertexFromBlock(ModelDoc2 swModel, View drView, double vScaleRat, bool up)
        {
            Ordinate vertex = null;
            var objSketchBlockDef = swModel.SketchManager.GetSketchBlockDefinitions();
            if (objSketchBlockDef != null)
            {
                var objSketBlDefs = (object[]) objSketchBlockDef;
                foreach (var objSketBlDef in objSketBlDefs)
                {
                    var swSketBlDef = (SketchBlockDefinition) objSketBlDef;

                    //if ((Path.GetFileNameWithoutExtension(swSketBlDef.FileName) == ("DS" + drView.Name) && up) ||
                       //(Path.GetFileNameWithoutExtension(swSketBlDef.FileName) == ("DE" + drView.Name) && !up))
                    {
                        var objSketBlInsts = (object[]) swSketBlDef.GetInstances();
                        if (objSketBlInsts != null)
                            foreach (var objSketBlInst in objSketBlInsts)
                            {
                                var swSketBlInst = (SketchBlockInstance) objSketBlInst;

                                if ((swSketBlInst.Name.Contains("DS" + drView.Name) && up) ||
                                    (swSketBlInst.Name.Contains("DE" + drView.Name) && !up))
                                {
                                    var pos = (double[]) drView.Position;
                                    var point = swSketBlInst.InstancePosition;
                                    var dims = (double[]) point.ArrayData;
                                    double y = dims[1]/vScaleRat;
                                    double x = dims[0]/vScaleRat;
                                    x = pos[0] + x;
                                    y = pos[1] + y;
                                    vertex = new Ordinate(x, y);
                                }
                            }
                    }

                }
            }
            return vertex;
        }
Beispiel #12
0
 public FoundCoordinate(ISldWorks swApp, Entity ent, Ordinate vertex, double[] dimLineH, double[] dimLineV, BlockPosition side,View swView,bool doThroughHoles)
 {
     _swApp = swApp;
     _swModel = swApp.IActiveDoc2;
     _side = side;
     _ent = ent;
     _vertex = vertex;
     _doThroughHoles = doThroughHoles;
     _swSelData = _swModel.ISelectionManager.CreateSelectData();
     _swView = swView;
     _coordinate = FindCoord(dimLineH, dimLineV);
 }
Beispiel #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;
            }
        }
Beispiel #14
0
        public void SaveDrawingV2()
        {
            //This callback is for a utility to save an un-saved drawing of a part with a BPA part number into the correct Vault directory with the correct file name.

            DrawingDoc swDraw = iSwApp.ActiveDoc;

            SolidWorks.Interop.sldworks.View swView = swDraw.IGetFirstView();
            swView = swView.GetNextView();
            ModelDoc2 swDrawModel   = swView.ReferencedDocument;
            int       errors        = 0;
            int       warnings      = 0;
            String    configName    = swView.ReferencedConfiguration;
            String    drawingNumber = swDrawModel.GetCustomInfoValue(configName, "Drawing Number");

            //MessageBox.Show("The drawing number is: " + drawingNumber);


            if (drawingNumber == "" || drawingNumber == " ")
            {
                MessageBox.Show("Please fill out the drawing number field on the model's file data card before proceeding.", "Missing Drawing Number", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            String modelPath = swDrawModel.GetPathName().ToString();

            MessageBox.Show("The model's path is: " + modelPath);
            if (modelPath == "" || modelPath == " ")
            {
                MessageBox.Show("Please save the model before proceeding", "Save the Model", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            swDrawModel = iSwApp.ActiveDoc;
            String swDrawPath = swDrawModel.GetPathName().ToString();

            //MessageBox.Show("The drawing path is: " + swDrawPath);
            if (swDrawPath != "")
            {
                MessageBox.Show("The drawing has already been saved as '" + swDrawPath + "' in the Vault.", "Drawng Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                string[]     pathDir       = modelPath.Split('\\');
                int          pathDirLength = pathDir.Length;
                string       path          = pathDir[0] + "\\" + pathDir[1] + "\\" + pathDir[2] + "\\" + pathDir[3] + "\\" + pathDir[4] + "\\";
                string       dwgPath       = path + drawingNumber + ".SLDDRW";
                string       dialogText    = "The drawing path is: \n" + dwgPath + "\nContinue?";
                DialogResult result        = MessageBox.Show(dialogText, "Save Drawing?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (result == DialogResult.OK)
                {
                    ModelDoc2 Model = SwApp.ActiveDoc;
                    Boolean   Save;
                    Save = Model.SaveAs4(dwgPath, 0, 1, errors, warnings);
                }
            }


            //ModelDocExtension swModExt = default(ModelDocExtension);
            //Return the filepath of the referenced model in the parent view in the active drawing document.
            //string swModel = swView.GetReferencedModelName();
        }
Beispiel #15
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);
            }
        }
Beispiel #16
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;
            }
        }
Beispiel #17
0
        private bool GetSelectedView(out View swView)
        {
            bool ret = false;
            swView = null;

            SelectionMgr swSelMgr = SwModel.ISelectionManager;
            if (swSelMgr.GetSelectedObjectCount() == 1)
            {
                if (swSelMgr.GetSelectedObjectType3(1, 0) == (int)swSelectType_e.swSelDRAWINGVIEWS)
                {
                    swView = (View)swSelMgr.GetSelectedObject6(1, 0);
                    ret = true;
                }
            }
            return ret;
        }
Beispiel #18
0
        /// <summary>
        /// 生成零件号
        /// </summary>
        private void CreatePartNumber()
        {
            ModelDoc2 swModel = (ModelDoc2)AllData.iSwApp.ActiveDoc;

            if (swModel == null)
            {
                return;
            }

            DrawingDoc swDraw = (DrawingDoc)swModel;

            if (swDraw == null)
            {
                return;
            }


            //序号为零件属性,还是项目号, 还是文字
            int    iTextContent = -1;
            string strText      = "";

            if (this.rdoTemp1.Checked)
            {
                iTextContent = (int)swBalloonTextContent_e.swBalloonTextItemNumber;
                strText      = "";
            }
            else if (this.rdoTemp2.Checked)
            {
                iTextContent = (int)swBalloonTextContent_e.swBalloonTextCustomProperties;
                strText      = Interop.Office.Core.Properties.Settings.Default.CreateNbr_PPtName; //"序号";
            }
            else if (this.rdoTemp3.Checked)
            {
                iTextContent = (int)swBalloonTextContent_e.swBalloonTextCustom;
                strText      = "0";
            }
            else if (this.rdoTemp4.Checked)
            {
                iTextContent = (int)swBalloonTextContent_e.swBalloonTextQuantity;
                strText      = "0";
            }


            //以正方形分布
            int iLayout = (int)swBalloonLayoutType_e.swDetailingBalloonLayout_Square;
            //下划线
            int iStyle = (int)swBalloonStyle_e.swBS_Underline;
            //下划线长度
            int iSize = (int)swBalloonFit_e.swBF_Tightest;


            //如果用户没有选中一个视图,就选中所有的视图
            SolidWorks.Interop.sldworks.View swView = (SolidWorks.Interop.sldworks.View)swDraw.ActiveDrawingView;
            if (swView == null)//对所有的视图进行重排序
            {
                swModel.ClearSelection2(true);
                swView = (SolidWorks.Interop.sldworks.View)swDraw.GetFirstView();
                while (swView != null)
                {
                    swModel.Extension.SelectByID2(swView.Name, "DRAWINGVIEW", 0, 0, 0, true, 0, null, 0);
                    swView = (SolidWorks.Interop.sldworks.View)swView.GetNextView();
                }
            }

            //自动添加序号
            swDraw.AutoBalloon3(iLayout, true, iStyle, iSize, iTextContent, strText, iTextContent, strText, "");


            //Notes = Part.AutoBalloon3(1, True, 10, 2, 1, "", 2, "", "-无-")

            //swDraw.AutoBalloon3(iLayout, true, iStyle, -1, iTextContent, "xh", iTextContent, "xh", "");
            //swDraw.AutoBalloon3(1, true, 10, 2, 1, "", 2, "", "-无-");

            //.AutoBalloon3(1, True, 10, 2, 1, "", 2, "", "-无-")
            ////SolidWorks2006
            //swDraw.AutoBalloon2((int)swBalloonLayoutType_e.swDetailingBalloonLayout_Top, true);
        }
Beispiel #19
0
        private void ProcessHole(View swView, DrawingHole drwhole, string blkname)
        {
            var mpoint = (MathPoint)(_iSwApp.IGetMathUtility()).CreatePoint(
                new[] { drwhole.Cx, drwhole.Cy, drwhole.Cz });

            if (blkname != "")
            {
                SketchBlockDefinition swSbDef = SwModel.SketchManager.MakeSketchBlockFromFile(mpoint, blkname, false, 1,
                                                                                              0);

                if (swSbDef == null)
                {
                    var swBDefs = (object[])SwModel.SketchManager.GetSketchBlockDefinitions();
                    if (swBDefs != null)
                    {
                        foreach (var swTestSbDef in
                            swBDefs.Cast<SketchBlockDefinition>().Where(swTestSbDef => swTestSbDef.FileName == blkname))
                        {
                            swSbDef = swTestSbDef;
                            break;
                        }
                    }
                }

                if (swSbDef != null)
                {
                    var swBInsts = (object[])swSbDef.GetInstances();
                    if (swBInsts != null)
                    {
                        foreach (object t in swBInsts)
                        {
                            var swSbInst = (SketchBlockInstance)t;
                            if (((Feature)swSbInst.GetSketch()).Name == ((Feature)swView.GetSketch()).Name)
                            {
                                swSbInst.Scale2 = drwhole.Radius * 2 * swView.ScaleDecimal * 1000;
                            }
                        }
                    }
                }
            }
            drwhole.IsProcessed = true;
        }
Beispiel #20
0
        /// <summary>
        /// 如果不是数字冲排序,而是重新指定文字,特别是一些复杂的组合,如【项目数X代号】
        /// </summary>
        private void SaidiResortOneView(SolidWorks.Interop.sldworks.View swView, ModelDoc2 swModel)
        {
            //101,$数量×$图号  ,$数量($属性名)等等各种格式
            string strText = this.cmbStartIndex.Text;

            //是否需要进行赛迪处理-页码-页数的时候,如果页数=1不显示,否则显示页码
            bool bSaidiCheck = false;


            char[]   carr   = new char[] { '(', ')', '×', 'x', 'X', '-', '_', '=', '(', ')', '[', ']', ' ', '/', '"' };
            string[] strArr = strText.Split(carr);

            //执行完切割后,要去掉引号,因为下面还要加引号
            strText = strText.Replace("\"", "");

            foreach (string s in strArr)
            {
                if (s != "$项目数" && s != "$项目号" && s.Length > 1)
                {
                    strText = strText.Replace(s, "$PRPMODEL:\"" + s.Trim(new char[] { '$' }) + "\"");//如"$项目数×$PRPMODEL:\"名称\"";
                }
            }
            bool bXMS = (strText.IndexOf("$项目数") != -1);
            bool bXMH = (strText.IndexOf("$项目号") != -1);

            int iTextQuantity = (int)swDetailingNoteTextContent_e.swDetailingNoteTextQuantity;       //数量
            int iTextNumber   = (int)swDetailingNoteTextContent_e.swDetailingNoteTextItemNumber;     //项目号
            int iTextProperty = (int)swDetailingNoteTextContent_e.swDetailingNoteTextCustomProperty; //属性

            //遍历注释
            Note not = (Note)swView.GetFirstNote();

            while (not != null)
            {
                if (not.IsBomBalloon())                               //只有符号这个条件才可以
                {
                    Annotation ann = (Annotation)not.GetAnnotation(); //必须要有Annotation
                    if (ann == null)
                    {
                        goto ABC;
                    }
                    object[] obArr = (object[])ann.GetAttachedEntities2();//必须要有Entities
                    if (obArr == null || obArr.Length == 0)
                    {
                        goto ABC;
                    }

                    Entity     ent  = (Entity)obArr[0];
                    Component2 comp = (Component2)ent.GetComponent();

                    //看看是否有重复的,一个配置只允许标注一次,如果需要多次标注,只能用不同的配置。
                    string FullPath = comp.GetPathName() + comp.ReferencedConfiguration;

                    //先复制一份值
                    string thisTxt = strText;
                    //如果有项目数,读取项目数
                    if (bXMS)
                    {
                        //选中这个注释,然后设为项目数
                        swModel.Extension.SelectByID2(not.GetName() + "@" + swView.Name, "NOTE", 0, 0, 0, true, 0, null, 0);
                        not.SetBomBalloonText(iTextQuantity, "", iTextQuantity, "");
                        string txt = not.GetText();
                        if (txt.Length > 0)
                        {
                            thisTxt = thisTxt.Replace("$项目数", txt);
                        }
                    }
                    //如果有项目号,读取项目号
                    if (bXMH)
                    {
                        //选中这个注释,然后设为项目号
                        swModel.Extension.SelectByID2(not.GetName() + "@" + swView.Name, "NOTE", 0, 0, 0, true, 0, null, 0);
                        not.SetBomBalloonText(iTextNumber, "", iTextNumber, "");
                        string txt = not.GetText();
                        if (txt.Length > 0)
                        {
                            thisTxt = thisTxt.Replace("$项目号", txt);
                        }
                    }

                    //如果是赛迪,当页数>1时,加上-页码,否侧不加-页码
                    //先列出-页数-页码来,然后再去掉-1-1
                    if (bSaidiCheck)
                    {
                        //先设置页数属性链接
                        not.SetBomBalloonText(iTextProperty, "$PRPMODEL:\"页数\"", iTextProperty, "$PRPMODEL:\"页数\"");
                        string s = not.GetText();
                        if (s.Length > 0 && s.Length < 4 && s != "1" && s != "0")
                        {
                            thisTxt = thisTxt.Replace("-$PRPMODEL:\"页数\"", "");
                        }
                        else
                        {
                            thisTxt = thisTxt.Replace("-$PRPMODEL:\"页码\"-$PRPMODEL:\"页数\"", "");
                        }
                    }

                    //最后设置新的文本
                    not.SetBomBalloonText(iTextProperty, thisTxt, iTextProperty, thisTxt);
                }
ABC:
                not = (Note)not.GetNext();
            }
        }
Beispiel #21
0
        /// <summary>
        /// 对于一个视图进行重排序,返回序号已经排到哪了
        /// </summary>
        private int ReSortOneView(int abc, SolidWorks.Interop.sldworks.View swView, ModelDoc2 swModel)
        {
            //先得到视图的对角线的三点坐标和比例//初始化视图
            this.GetViewThreePointAndScale(swView);

            //排序用
            ArrayList arSort = new ArrayList();
            //保存数据
            Hashtable ht = new Hashtable();
            //保存数据
            Hashtable ht2 = new Hashtable();
            //是否有在右上方的//如果没有则为0,否则保在最上方的最大值,如果最大值<0.15,说明虽然有在上方的,但可以忽略,因为离左上角很进.
            double dAtTopMaxValue = 0;


            //遍历注释
            Note not = (Note)swView.GetFirstNote();

            while (not != null)
            {
                if (not.IsBomBalloon())                               //只有符号这个条件才可以
                {
                    Annotation ann = (Annotation)not.GetAnnotation(); //必须要有Annotation
                    if (ann == null)
                    {
                        goto ABC;
                    }
                    object[] obArr = (object[])ann.GetAttachedEntities2();//必须要有Entities
                    if (obArr == null || obArr.Length == 0)
                    {
                        goto ABC;
                    }

                    Entity     ent  = (Entity)obArr[0];
                    Component2 comp = (Component2)ent.GetComponent();

                    //看看是否有重复的,一个配置只允许标注一次,如果需要多次标注,只能用不同的配置。
                    string FullPath = comp.GetPathName() + comp.ReferencedConfiguration;
                    if (arCheckRepect.Contains(FullPath))
                    {
                        goto ABC;
                    }
                    else
                    {
                        arCheckRepect.Add(FullPath);
                    }

                    //string txt = not.GetText();
                    double[] dbArr = (double[])not.GetTextPoint2();

                    //计算角度
                    double dAngle = GetAngelByNotePoint(dbArr[0], dbArr[1]);

                    if (CheckUnderOrUpTheLine(dbArr[0], dbArr[1]) == true)//在上方//升序
                    {
                        if (dAtTopMaxValue < dAngle)
                        {
                            dAtTopMaxValue = dAngle;                         //保存这个角度//这个角度是上方角度的最大值
                        }
                    }
                    else//下方的//降序
                    {
                        dAngle = 15 - dAngle;//dAngle一般不会大于二
                    }

                    arSort.Add(dAngle);    //排序
                    ht.Add(dAngle, not);   //保存数据
                    ht2.Add(dAngle, comp); //防止再算一遍
                }
ABC:
                not = (Note)not.GetNext();
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////
            arSort.Sort();//排序
            if (dAtTopMaxValue < 0.15)
            {
                arSort.Reverse();                       //如果上方没有,或靠近左上角的地方有一两个(Angle<0.15),下方的也不会按DESC排序
            }
            /////////////////////////////////////////////////////////////////////////////////////////////////


            //序号为项目号,还是零件属性,还是文本
            int    iTextContent = -1;
            string strText      = "";

            if (this.rdoTemp1.Checked)
            {
                iTextContent = (int)swDetailingNoteTextContent_e.swDetailingNoteTextItemNumber;
                strText      = "";
            }
            else if (this.rdoTemp2.Checked)
            {
                iTextContent = (int)swDetailingNoteTextContent_e.swDetailingNoteTextCustomProperty;
                strText      = "$PRPMODEL:\"序号\"";
            }
            else if (this.rdoTemp3.Checked)
            {
                iTextContent = (int)swDetailingNoteTextContent_e.swDetailingNoteTextCustom;
                strText      = "";
            }
            else if (this.rdoTemp4.Checked)
            {
                iTextContent = (int)swBalloonTextContent_e.swBalloonTextQuantity;
                strText      = "0";
            }


            //开始修改
            for (int i = 0; i < arSort.Count; i++)
            {
                Note       notsub = (Note)ht[arSort[i]];
                Component2 comp   = (Component2)ht2[arSort[i]];

                //选中这个注释
                swModel.Extension.SelectByID2(notsub.GetName() + "@" + swView.Name, "NOTE", 0, 0, 0, true, 0, null, 0);

                if (this.rdoTemp2.Checked)
                {
                    this.swm.SetAtrByCompAndAtrName(comp, "序号", abc);//设置属性,并保存到零件
                }
                else
                {
                    strText = abc.ToString();//序号
                }

                //notsub.PropertyLinkedText = "$PRPMODEL:\"序号\"";//这样可能也可以
                notsub.SetBomBalloonText(iTextContent, strText, iTextContent, strText);

                //////////////////////////////////////////////////////////////////////
                //检查看看是否正确,如果不正确,再设置,这里没起到任何作用
                string txt = notsub.GetText();
                if (txt != abc.ToString())
                {
                    notsub.SetText(abc.ToString());
                }
                ///////////////////////////////////////////////////////////////////////

                abc++;
            }
            return(abc);
        }
Beispiel #22
0
        /// <summary>
        /// 如果有一个视图为选中状态,则对这个视图进行重排序,
        /// 否则,对一个图纸下的所有视图进行重排序
        /// </summary>
        private void ReSortAllView()
        {
            this.arCheckRepect.Clear();
            if (this.rdoTemp1.Checked)
            {
                if (StringOperate.Alert("序号为项目号时,无法重排序,要继续吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }
            }

            ModelDoc2 swModel = (ModelDoc2)AllData.iSwApp.ActiveDoc;

            if (swModel == null)
            {
                return;
            }

            DrawingDoc   swDraw = (DrawingDoc)swModel;
            SelectionMgr SelMgr = (SelectionMgr)swModel.SelectionManager;

            swModel.ClearSelection2(true);

            //101,$数量×"序号",$数量×"属性名"
            string strTxt = this.cmbStartIndex.Text;
            int    abc    = 1;
            bool   bText  = false;

            try
            {
                abc = Convert.ToInt16(this.cmbStartIndex.Text);//序号从一开始
            }
            catch
            {
                bText = true;
            }

            SolidWorks.Interop.sldworks.View swView = (SolidWorks.Interop.sldworks.View)swDraw.ActiveDrawingView;
            if (swView == null)//对所有的视图进行重排序
            {
                swView = (SolidWorks.Interop.sldworks.View)swDraw.GetFirstView();
                //遍历视图
                while (swView != null)
                {
                    swDraw.ActivateView(swView.Name);

                    if (bText)
                    {
                        SaidiResortOneView(swView, swModel);//对这个视图进行排序
                    }
                    else
                    {
                        abc = ReSortOneView(abc, swView, swModel);//对这个视图进行排序
                    }

                    //转到下一个视图
                    swView = (SolidWorks.Interop.sldworks.View)swView.GetNextView();
                }
            }
            else//只对当前视图进行重排序
            {
                if (bText)
                {
                    SaidiResortOneView(swView, swModel);//对这个视图进行排序
                }
                else
                {
                    ReSortOneView(abc, swView, swModel);
                }
            }

            //重建,以更新明细表
            swModel.EditRebuild3();

            this.arCheckRepect.Clear();
        }