public JointAxis(SldWorks swApp, AssemblyDoc asm, StorageModel swData, string path, Joint current, int index, RobotModel robot) { this.swApp = swApp; this.asmDoc = asm; this.modelDoc = (ModelDoc2)asm; this.swData = swData; this.path = path; this.owner = current; this.robot = robot; this.AxisIndex = index; if (EffortLimit == 0) { this.EffortLimit = 1; } if (this.VelocityLimit == 0) { this.VelocityLimit = 1; } if (Axis != null) { CalcAxisVectors(); //CalcLimits(null); } if (index == 2) { IsContinuous = true; } }
public DocumentEventHandler(ModelDoc2 modDoc, SwAddin addin) { Document = modDoc; UserAddin = addin; SwApp = UserAddin.SwApp; OpenModelViews = new Hashtable(); }
public DocumentEventHandler(ModelDoc2 modDoc, SwAddin addin) { document = modDoc; userAddin = addin; iSwApp = (ISldWorks)userAddin.SwApp; openModelViews = new Hashtable(); }
public AssemblyEventHandler(ModelDoc2 modDoc, SwAddin addin) : base(modDoc, addin) { doc = (AssemblyDoc)document; swModel = modDoc; swAddin = addin; }
internal static void AddModelToList(SwAddin mSwAddin, ModelDoc2 newModel) { List<ModelDoc2> fM = null; string xNameOfAss = mSwAddin.GetXNameForAssembly(false, Path.GetFileNameWithoutExtension(mSwAddin.SwModel.GetPathName())); #region Проверка на наличие модели,которая была удалена var checkList = new List<ModelDoc2>(); if (!DictionaryListMdb.ContainsKey(xNameOfAss)) DictionaryListMdb.Add(xNameOfAss, new List<ModelDoc2>()); foreach (var m in DictionaryListMdb[xNameOfAss]) { try { m.GetPathName(); checkList.Add(m); } catch (COMException) { continue; } } #endregion if (!checkList.Contains(newModel)) CheckMdbForDecors(mSwAddin, newModel, checkList, null, fM); DictionaryListMdb[xNameOfAss] = checkList; }
/// <summary> /// Sets the current robot that is linked to this page /// </summary> /// <param name="robot">robot to be used</param> /// <param name="model">model to be used</param> public void setRobot(RobotModel robot, ModelDoc2 model) { this.robot = robot; robotName.Text = robot.Name; string[] configurations = model.GetConfigurationNames(); IncludeFRCfieldBox.Visible = PluginSettings.UseFRCsim; if (PluginSettings.UseFRCsim) { switch (robot.FRCfield) { case 2014: FRC2014FieldButton.Checked = true; break; case 2015: FRC2015FieldButton.Checked = true; break; default: NoFieldButton.Checked = true; break; } } if (robot.ExportType == 0) SDFExportTypeButton.Checked = true; else URDFExportTypeButton.Checked = true; }
public frmFullPrice(ModelDoc2 model) { InitializeComponent(); CurrentState = State.ErrorsHide; this.model = model; }
public frmCopyProject(SwAddin swAdd,ISldWorks iswApp,ModelDoc2 rootModel,string openFile) { _swAdd = swAdd; _iswApp = iswApp; _swModelDoc = rootModel; _openFile = openFile; InitializeComponent(); WarningLabel.Text = string.Empty; }
public KitchenModule(ModelDoc2 _rootModel, Component2 _swRootComponent, SwAddin _swAddin, ModelDoc2 _swModel) { RootModel = _rootModel; swRootComponent = _swRootComponent; measure = RootModel.Extension.CreateMeasure(); swAddin = _swAddin; swModel = _swModel; rootName = Path.GetFileNameWithoutExtension(RootModel.GetPathName()); }
public FrmReplaceComponents(SwAddin swAddin, Component2[] selComps) { InitializeComponent(); _mSwAddin = swAddin; _mSelComps = selComps; _swModel = (ModelDoc2)_mSwAddin.SwApp.ActiveDoc; Show(); }
public void TestLoadSWComponentsList(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); List <Component2> components = Common.LoadSWComponents(doc, baseNode.Link.SWComponentPIDs); Assert.Equal(baseNode.Link.SWComponentPIDs.Count, components.Count); SwApp.CloseAllDocuments(true); }
public void TestSaveSWComponentsList(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; object[] componentObjs = assyDoc.GetComponents(false); List <Component2> components = componentObjs.Cast <Component2>().ToList(); List <byte[]> pids = Common.SaveSWComponents(doc, components); Assert.Equal(pids.Count, components.Count); SwApp.CloseAllDocuments(true); }
/// <summary> /// Creates a new Specific Joint object /// </summary> /// <param name="joint">The joint that this joint is in</param> /// <param name="path">The storage path for this joint</param> protected JointSpecifics(Joint joint, string path) { this.robot = RobotInfo.Robot; this.joint = joint; this.swApp = RobotInfo.SwApp; this.modelDoc = RobotInfo.ModelDoc; this.swData = RobotInfo.SwData; this.path = path; OriginValues = new OriginPoint(); if(OriginPt != null) OriginValues.Point = GetPointFromEntity(OriginPt); }
/// <summary> /// 获取当前激活文档的文件名 /// </summary> /// <returns></returns> public static string GetActiveDocName() { StartSW(); ModelDoc2 swDoc = swApp.ActiveDoc; if (swDoc == null) { return("error"); } string fileName = swDoc.GetPathName(); return(fileName); }
public void OpenInExplorer() { ModelDoc2 swModel = iSwApp.ActiveDoc; string swModelPath = swModel.GetPathName(); swModelPath = "/select, " + swModelPath; System.Diagnostics.Process Process = new System.Diagnostics.Process(); Process.StartInfo.UseShellExecute = true; Process.StartInfo.FileName = @"explorer"; Process.StartInfo.Arguments = swModelPath; Process.Start(); }
private void btnPack_Click(object sender, EventArgs e) { ISldWorks swApp = Utility.ConnectToSolidWorks(); ModelDoc2 swModel = swApp.ActiveDoc; //CopySolidworksFile(txtFrom.Text, txtTo.Text, "", ""); progressBarCopy.Value = 5; CopySolidworksFile(txtFrom.Text, txtTo.Text); progressBarCopy.Value = 100; MessageBox.Show("操作完成"); progressBarCopy.Value = 0; }
private void createPart() { swDoc = null; int longstatus = 0; swDoc = ((ModelDoc2)(sldApp.NewDocument("C:\\ProgramData\\SOLIDWORKS\\SOLIDWORKS 2016\\templates\\Part.prtdot", 0, 0, 0))); sldApp.ActivateDoc2("Part2", false, ref longstatus); swDoc = ((ModelDoc2)(sldApp.ActiveDoc)); ModelView myModeview = null; myModeview = ((ModelView)(swDoc.ActiveView)); myModeview.FrameState = ((int)(swWindowState_e.swWindowMaximized)); }
public void AttachEventsToAllDocuments() { ModelDoc2 modDoc = (ModelDoc2)iSwApp.GetFirstDocument(); while (modDoc != null) { if (!openDocs.Contains(modDoc)) { AttachModelDocEventHandler(modDoc); } modDoc = (ModelDoc2)modDoc.GetNext(); } }
/// <summary> /// 模型打包 /// </summary> /// <param name="suffix">后缀</param> /// <param name="swApp">SW程序</param> /// <param name="modelPath">模型地址</param> /// <param name="itemPath">目标地址</param> /// <returns></returns> public static string PackAndGoFunc(string suffix, SldWorks swApp, string modelPath, string itemPath) { swApp.CommandInProgress = true; int warnings = 0; int errors = 0; ModelDoc2 swModelDoc = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); PackAndGo swPackAndGo = default(PackAndGo); //打开需要pack的模型 swModelDoc = (ModelDoc2)swApp.OpenDoc6(modelPath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swModelDocExt = (ModelDocExtension)swModelDoc.Extension; swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo(); // Get number of documents in assembly //namesCount = swPackAndGo.GetDocumentNamesCount(); //Debug.Print(" Number of model documents: " + namesCount); // Include any drawings, SOLIDWORKS Simulation results, and SOLIDWORKS Toolbox components swPackAndGo.IncludeDrawings = false; swPackAndGo.IncludeSimulationResults = false; swPackAndGo.IncludeToolboxComponents = false; // Set folder where to save the files,目标存放地址 swPackAndGo.SetSaveToName(true, itemPath); //将文件展开到一个文件夹内,不要原始模型的文件夹结构 // Flatten the Pack and Go folder structure; save all files to the root directory swPackAndGo.FlattenToSingleFolder = true; // Add a prefix and suffix to the filenames //swPackAndGo.AddPrefix = "SW_";添加后缀 swPackAndGo.AddSuffix = "_" + suffix; try { // Pack and Go,执行PackAndGo swModelDocExt.SavePackAndGo(swPackAndGo); } catch (Exception ex) { throw new Exception("PackandGo过程中出现异常:" + ex.Message); } finally { swApp.CloseDoc(swModelDoc.GetTitle()); swModelDoc = null; swApp.CommandInProgress = false;//及时关闭外部命令调用,否则影响SolidWorks的使用 } string modelPathName = modelPath.Substring(modelPath.LastIndexOf(@"\") + 1); //返回packandgo后模型的地址 return(itemPath + @"\" + modelPathName.Substring(0, modelPathName.LastIndexOf(".")) + "_" + suffix + ".sldasm"); }
private void button1_Click(object sender, EventArgs e) { if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); pictureBox1.Image = null; pictureBox1.Load(); pictureBox1.Update(); } SldWorks sw = new SldWorks(); sw.Visible = true; int err = 0, war = 0; ModelDoc2 swModel = sw.OpenDoc6(Application.StartupPath + "\\cylinder.sldprt", 1, 0, "", ref err, ref war); double[] props = swModel.GetMassProperties(); textBox1.Text = props[5].ToString(); IRayTraceRenderer swRayTraceRenderer = sw.GetRayTraceRenderer(1); if (swRayTraceRenderer == null) { int fileerror = sw.LoadAddIn("PhotoView 360"); swRayTraceRenderer = sw.IGetRayTraceRenderer(1); } RayTraceRendererOptions swRayTraceRenderOptions = swRayTraceRenderer.RayTraceRendererOptions; textBox2.Clear(); textBox2.Text += "Current rendering values"; textBox2.Text += System.Environment.NewLine + "ImageWidth = " + (swRayTraceRenderOptions.ImageWidth); textBox2.Text += System.Environment.NewLine + "ImageFormat = " + (swRayTraceRenderOptions.ImageFormat); textBox2.Text += System.Environment.NewLine + "ImageHeight = " + (swRayTraceRenderOptions.ImageHeight); textBox2.Text += System.Environment.NewLine + "PreviewRenderQuality = " + (swRayTraceRenderOptions.PreviewRenderQuality); textBox2.Text += System.Environment.NewLine + "FinalRenderQuality = " + (swRayTraceRenderOptions.FinalRenderQuality); textBox2.Text += System.Environment.NewLine + "BloomEnabled = " + (swRayTraceRenderOptions.BloomEnabled); textBox2.Text += System.Environment.NewLine + "BloomThreshold = " + (swRayTraceRenderOptions.BloomThreshold); textBox2.Text += System.Environment.NewLine + "BloomRadius = " + (swRayTraceRenderOptions.BloomRadius); textBox2.Text += System.Environment.NewLine + "ContourEnabled = " + (swRayTraceRenderOptions.ContourEnabled); textBox2.Text += System.Environment.NewLine + "ShadedContour = " + (swRayTraceRenderOptions.ShadedContour); textBox2.Text += System.Environment.NewLine + "ContourLineThickness = " + (swRayTraceRenderOptions.ContourLineThickness); textBox2.Text += System.Environment.NewLine + "ContourLineColor = " + (swRayTraceRenderOptions.ContourLineColor); bool status = swRayTraceRenderer.RenderToFile(Application.StartupPath + "./lter_1.jpg", 0, 0); status = swRayTraceRenderer.CloseRayTraceRender(); pictureBox1.Load(Application.StartupPath + "./lter_1.jpg"); }
private void ExportButtonClick(object sender, EventArgs e) { swModelDoc = swApp.ActiveDoc; swModelDocExt = swModelDoc.Extension; swAssDoc = swApp.ActiveDoc as AssemblyDoc; swFeat = (Feature)swModelDoc.FirstFeature(); swFeatMgr = (FeatureManager)swModelDoc.FeatureManager; while ((swFeat != null)) { sFeatType = swFeat.GetTypeName(); if (sFeatType == "CommentsFolder") { swCommentFolder = (CommentFolder)swFeat.GetSpecificFeature2(); nbrComments = swCommentFolder.GetCommentCount(); vComments = (object[])swCommentFolder.GetComments(); for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.HideComponent(); } for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.ShowComponent(); swModelDocExt.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swFileSaveAsCoordinateSystem, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, "CoordinateSystem"); swModelDocExt.SaveAs("C:/Users/Izmar/Documents/vmpc_models/jan2018/stlexport/" + swComment.Text + ".STL", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, 0, ref errors, ref warnings); swAssDoc.HideComponent(); } for (i = 0; i <= (nbrComments - 1); i++) { swComment = (Comment)vComments[i]; string name = swComment.Name; Component2 comp = swAssDoc.GetComponentByName(name); swModelDocExt.SelectByID2(comp.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); swAssDoc.ShowComponent(); } } // Get next feature in FeatureManager design tree swFeat = (Feature)swFeat.GetNextFeature(); } }
//Finds the selected components and returns them, used when pulling the items from the selection box because it would be too hard // for SolidWorks to allow you to access the selectionbox components directly. public static void getSelectedComponents(ModelDoc2 model, List<Component2> Components, int Mark = -1) { SelectionMgr selectionManager = model.SelectionManager; Components.Clear(); for (int i = 0; i < selectionManager.GetSelectedObjectCount2(Mark); i++) { object obj = selectionManager.GetSelectedObject6(i + 1, Mark); Component2 comp = (Component2)obj; if (comp != null) { Components.Add(comp); } } }
//Except for an exclusionary list, this shows all the components public static void showAllComponents(ModelDoc2 model, List<string> hiddenComponents) { AssemblyDoc assyDoc = (AssemblyDoc)model; List<Component2> componentsToShow = new List<Component2>(); object[] varComps = assyDoc.GetComponents(false); foreach (Component2 comp in varComps) { if (!hiddenComponents.Contains(comp.Name2)) { componentsToShow.Add(comp); } } showComponents(model, componentsToShow); }
public void ClearProps(ModelDoc2 md) { CustomPropertyManager glP = md.Extension.get_CustomPropertyManager(string.Empty); int res; for (int i = 1; i <= Properties.Settings.Default.RevLimit; i++) { res = glP.Delete2("REVISION " + (char)(i + 65)); res = glP.Delete2("ECO " + i.ToString()); res = glP.Delete2("DESCRIPTION " + i.ToString()); res = glP.Delete2("LIST " + i.ToString()); res = glP.Delete2("DATE " + i.ToString()); } }
public static List <object> GetSelectedFaces(SldWorks swApplication, ModelDoc2 swModel) { swModel = swApplication.ActiveDoc; var swSafeEntityList = new List <object>(); var modelType = swModel.GetTitle(); var documentType = (swDocumentTypes_e)swModel.GetType(); if (documentType == swDocumentTypes_e.swDocPART) { var myPartDoc = (PartDoc)swModel; Array myBodyVar = myPartDoc.GetBodies2((int)swBodyType_e.swAllBodies, true); int myBodyCount = 0; for (myBodyCount = myBodyVar.GetLowerBound(0); myBodyCount <= myBodyVar.GetUpperBound(0); myBodyCount++) { var myBodyComparison = (Body2)myBodyVar.GetValue(myBodyCount); var swFace = (Face2)myBodyComparison.GetFirstFace(); while (swFace != null) { var idNode = swFace.GetHashCode(); swFace.SetFaceId(idNode); swFace = swFace.GetNextFace(); } } var mySelManager = (SelectionMgr)swModel.SelectionManager; var selectionCount = mySelManager.GetSelectedObjectCount2(-1); //swApplication.SendMsgToUser("Numero oggetti selezionati " + selectionCount.ToString()); for (int i = 0; i < selectionCount; i++) { var myFace = (Face2)mySelManager.GetSelectedObject6(i + 1, -1); // var idNode = myFace.GetHashCode(); // myFace.SetFaceId(idNode); var swEntity = ((Entity)myFace).GetSafeEntity(); var swSafeEntity = (Entity)swEntity.GetSafeEntity(); swSafeEntityList.Add(swSafeEntity); } } //var listFace = new List<Face2>(); //swApplication.SendMsgToUser("Lista facce " + listFace.Count.ToString()); //foreach (Face2 face2 in listFace) //{ // swApplication.SendMsgToUser("Id: " + face2.GetFaceId().ToString()); //} //ColorFace.KLColorFace(listFace, swApplication); return(swSafeEntityList); }
private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { this.Close(); } else if (e.Key == Key.S && e.KeyboardDevice.IsKeyDown(Key.LeftCtrl)) { SaveAll(); } else if (e.Key == Key.F5) { SwModel = (ModelDoc2)SwApp.ActiveDoc; if (SwModel != null) { if (((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocPART) && ((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)) { MessageBox.Show("当前文件不是零件或装配体文件!"); Environment.Exit(0); } } else { MessageBox.Show("请打开零件或装配体文件!"); Environment.Exit(0); } SwConfigMgr = SwModel.ConfigurationManager; SwModelExt = SwModel.Extension; SwCustPropMgr = SwModelExt.get_CustomPropertyManager(""); string[] configNames = null; configNames = (string[])SwModel.GetConfigurationNames(); CboxConfigName.Items.Clear(); for (int i = 0; i < configNames.Length; i++) { CboxConfigName.Items.Add(configNames[i]); if (configNames[i].Contains(SwConfigMgr.ActiveConfiguration.Name)) { CboxConfigName.Text = SwConfigMgr.ActiveConfiguration.Name; } } DatePickerDesignDate.SelectedDate = DateTime.Today; TextColorReset(); TextBlock.Text = "已成功连接到SolidWorks文件! 按F5重新载入!"; } }
private void traverse(Component2 comp) { object[] childrens = comp.GetChildren(); foreach (Component2 child in childrens) { traverse(child); } ModelDoc2 mdocChild = comp.GetModelDoc2(); if (mdocChild.GetType() == 1) { // Bezeichnung kann über 2 Möglichkeiten erfolgen // Dateiname (mit GetFileName wird nur der Dateiname aus einem Dateipfad extrahiert string entry = System.IO.Path.GetFileName(comp.GetPathName()); // oder string entry2 = comp.Name2; //entfernen der 2 hinteren Zeichen im String entry2 = entry2.Remove(entry2.Length - 2); int Row = 0; // überprüfen, ob aktueller Eintrag bereits vorhanden ist, wenn ja Zeilen-Index speichern for (int i = 2; i < index; i++) { if ((string)exlSheet.Cells[i, 3].Value2 == entry) { Row = i; } } // wenn Zeilen Index gesetzt wurde, Wert für Anzahl aus Zeile lesen und um 1 erhöhen // erhöhten Wert in Zelle schreiben if (Row > 0) { double newCount = (double)exlSheet.Cells[Row, 1].Value2 + 1; exlSheet.Cells[Row, 1] = newCount; } else { // Wenn ZeilenIndex nicht gesetzt wurde, neuen Dateipfad exlSheet.Cells[index, 1] = 1; exlSheet.Cells[index, 2] = "Stück"; exlSheet.Cells[index, 3] = entry; lb_output.Items.Add(entry); index++; } } }
public ModelDoc2 OpenSwAssembly(string path) { ModelDoc2 swModel = default(ModelDoc2); DocumentSpecification swDocSpecification = default(DocumentSpecification); string[] componentsArray = new string[1]; object[] components = null; string name = null; int errors = 0; int warnings = 0; //Set the specifications swDocSpecification = (DocumentSpecification)app.GetOpenDocSpec(path); componentsArray[0] = "food bowl-1@bowl and chute"; components = (object[])componentsArray; swDocSpecification.ComponentList = components; swDocSpecification.Selective = true; name = swDocSpecification.FileName; swDocSpecification.DocumentType = (int)swDocumentTypes_e.swDocASSEMBLY; swDocSpecification.DisplayState = "Default_Display State-1"; swDocSpecification.UseLightWeightDefault = false; swDocSpecification.LightWeight = true; swDocSpecification.Silent = true; swDocSpecification.IgnoreHiddenComponents = true; //Open the assembly document as per the specifications swModel = (ModelDoc2)app.OpenDoc7(swDocSpecification); errors = swDocSpecification.Error; warnings = swDocSpecification.Warning; Debugger.Break(); if (errors > 0) { throw new Exception("Error while opening Solidworks assembly"); } if (warnings > 0) { System.Diagnostics.Debug.WriteLine("Warning while opening Soliworks assembly"); } activeModel = swModel; return(swModel); }
public SWglTFModel ConvertToglTFModel(ModelDoc2 swModel, out ErrorType errors) { SWglTFModel model = null; errors = ErrorType.DoNotKnow; ProgressStatus_event(0.01, "开始读取", ErrorType.NoErros); swDocumentTypes_e ModelType = (swDocumentTypes_e)swModel.GetType(); switch (ModelType) { case swDocumentTypes_e.swDocNONE: errors = ErrorType.NoPartOrAssemblyDocument; return(null); case swDocumentTypes_e.swDocPART: ProgressStatus_event(0.02, "读取零件信息", ErrorType.NoErros); model = ConvertPartToglTF(swModel); ProgressStatus_event(0.5, "读取零件信息完成", ErrorType.NoErros); break; case swDocumentTypes_e.swDocASSEMBLY: ProgressStatus_event(0.02, "读取装配体信息", ErrorType.NoErros); model = ConvertAssemblyToglTF(swModel); ProgressStatus_event(0.5, "读取装配体信息完成", ErrorType.NoErros); break; case swDocumentTypes_e.swDocDRAWING: errors = ErrorType.NoPartOrAssemblyDocument; return(null); case swDocumentTypes_e.swDocSDM: errors = ErrorType.NoPartOrAssemblyDocument; return(null); case swDocumentTypes_e.swDocLAYOUT: errors = ErrorType.NoPartOrAssemblyDocument; return(null); case swDocumentTypes_e.swDocIMPORTED_PART: break; case swDocumentTypes_e.swDocIMPORTED_ASSEMBLY: break; } if (model == null) { errors = ErrorType.DoNotKnow; } return(model); }
public void TestSerializeToString(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool error); Xunit.Assert.False(error); PrivateType serialization = new PrivateType(typeof(Serialization)); string newData = (string)serialization.InvokeStatic( "SerializeToString", new object[] { baseNode }); Xunit.Assert.NotNull(newData); Xunit.Assert.NotEmpty(newData); }
//Selects components from a list. public static void selectComponents(ModelDoc2 model, List<Component2> components, bool clearSelection = true, int mark = -1) { if (clearSelection) { model.ClearSelection2(true); } SelectionMgr manager = model.SelectionManager; SelectData data = manager.CreateSelectData(); data.Mark = mark; foreach (Component2 component in components) { component.Select4(true, data, false); } }
public void TestLoadSWComponentsLinkNode(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); List <string> problemLinks = new List <string>(); Common.LoadSWComponents(doc, baseNode, problemLinks); Assert.Empty(problemLinks); SwApp.CloseAllDocuments(true); }
//Converts SW component references to PIDs public static List <byte[]> SaveSWComponents(ModelDoc2 model, List <Component2> components) { List <byte[]> PIDs = new List <byte[]>(); foreach (Component2 component in components) { byte[] PID = SaveSWComponent(model, component); if (PID != null) { PIDs.Add(PID); } } return(PIDs); }
public static bool IsSheetMetal(this ModelDoc2 model) { if (model is PartDoc == false) { return(false); } if (model.HasFlatPattern() == false) { return(false); } return(true); }
// Строит или изменяет модель public void Build() { InitAndRunSwApp(); // имена размеров в документе полумуфты string fingerParameter1 = "fingers@Круговой массив1"; string fingerParameter2 = "fingers@Круговой массив2"; string nomianalDiameterParameter = "nominalDiameter@Эскиз1"; // имя полумуфты в сборке (имя компонента верхнего уровня) string assemblyPolumuftaName = "Полумуфта-1"; // Менеджер выделения, выбора SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager; // удалить выделение swModel.ClearSelection2(true); Component2 swComp = assembly.GetComponentByName(assemblyPolumuftaName); // выбрать полумуфту, не добавлять к выбранным, дата?, показать всплывающее кокшко swComp.Select4(false, null, false); int info = 0; // начать изменение полумуфты assembly.EditPart2(false, false, ref info); // получить редактируемую модель ModelDoc2 polumufta = (ModelDoc2)assembly.GetEditTarget(); // установка изменяемых параметров для всех конфигураций polumufta.Parameter(fingerParameter1).SetSystemValue3( countFingers, (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations ); polumufta.Parameter(fingerParameter2).SetSystemValue3( countFingers, (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations ); polumufta.Parameter(nomianalDiameterParameter).SetSystemValue3( nominalDiameter, (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations ); // ?? bool retVal = polumufta.EditSuppress2(); //Debug.Assert(retVal); // ?? assembly.EditAssembly(); swModel.EditRebuild3(); swModel.ForceRebuild3(false); swModel.ViewZoomtofit2(); }
public static byte[] ModelToBytes(ModelDoc2 model) { try { string fileName = model.GetTitle() + ".SLDPRT"; if (model.GetPathName() == null || model.GetPathName().Length == 0) { MessageBox.Show("Please, save model before adding!", "Search 3d Models", MessageBoxButtons.OK); MessageBox.Show("Model in DB will be with with name, that was in 'Model Name' input box!", "Attention!", MessageBoxButtons.OK); bool boolstatus = model.Save3((int)swSaveAsOptions_e.swSaveAsOptions_SaveReferenced, 0, 0); } string sourcePath = model.GetPathName(); string targetPath; if (GetModelsFolder() == null || GetModelsFolder().Length == 0) { string myDocuments = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); targetPath = myDocuments + @"\Search3DModels\Temp\"; } else { targetPath = GetModelsFolder() + @"\Temp\"; } string destinationFile = System.IO.Path.Combine(targetPath, fileName); if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } System.IO.File.Copy(sourcePath, destinationFile, true); FileStream fs = new FileStream(destinationFile, FileMode.Open, FileAccess.Read); byte[] modelInBytes = new byte[fs.Length]; fs.Read(modelInBytes, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); Directory.Delete(targetPath, true); return(modelInBytes); } catch (Exception exp) { MessageBox.Show(exp.StackTrace, "modelToBytes()", MessageBoxButtons.OK); } return(null); }
private static void LerBOM(BomTableAnnotation swBomTable, ModelDoc2 swModel) { TableAnnotation tabela = (TableAnnotation)swBomTable; long coluna = tabela.ColumnCount; long linha = tabela.RowCount; listaDeCodigos.Add(Path.GetFileNameWithoutExtension(swModel.GetPathName()) + ";"); for (int i = 0; i < linha - 1; i++) { listaDeCodigos.Add((tabela.Text[i, 1] + ";" + tabela.Text[i, 5])); } listaDeCodigos.Add(";"); }
public SwDrawing(ModelDoc2 drawModel) //Инициализация из класса модели { _drawModel = drawModel; if (_drawModel.GetType() == (int)DocType) { _swApp = SwProcess.swApp; _swDraw = (DrawingDoc)_drawModel; Debug.Print("SwDrawing initialised"); } else { throw new System.TypeLoadException("Модель не является чертежом"); } }
public static void AddAll(SldWorks swApp, ModelDoc2 parentDoc, List <KeyValuePair <string, string> > properties) { swApp.ActivateDoc(parentDoc.GetTitle()); var configuration = ((Configuration)parentDoc.GetActiveConfiguration()).Name; MessageBox.Show("configuration - " + configuration); var swCustProp = parentDoc.Extension.CustomPropertyManager[configuration]; foreach (var property in properties) { MessageBox.Show(property.Key + " - " + property.Value, "Свойство для добавления"); AddProperty(swCustProp, property); } }
public void makeDimensions(ModelDoc2 swModel) { foreach (string[] list in pack) { swModel.ClearSelection2(true); for (int i = 6; i < list.Length; i++) { SmartTools.SelectByID(swModel, list[i]); } swModel.AddDimension2(Convert.ToDouble(list[3]), Convert.ToDouble(list[4]), Convert.ToDouble(list[5])); } }
public void makeBindings(ModelDoc2 swModel) { foreach (string[] list in pack) { swModel.ClearSelection2(true); for (int i = 1; i < list.Length; i++) { SmartTools.SelectByID(swModel, list[i]); } swModel.SketchAddConstraints(list[0]); } }
static public List <ColumnNameEditPropTable> ListColumnToEditProp(ModelDoc2 swModel) { var columnRow = new List <ColumnNameEditPropTable>(); object[] configNamesDll = swModel.GetConfigurationNames(); foreach (string configName in configNamesDll) { Configuration swConf = swModel.GetConfigurationByName(configName); if (swConf.IsDerived() == false) { var customPropMan = swModel.Extension.CustomPropertyManager[configName]; var valOut = ""; var number = ""; var description = ""; var matName = ""; var thickness = ""; var codFb = ""; customPropMan.Get4("Обозначение", true, out valOut, out number); customPropMan.Get4("Наименование", true, out valOut, out description); customPropMan.Get4("Код_ФБ", true, out valOut, out codFb); customPropMan.Get4("Материал_Таблица", true, out valOut, out matName); customPropMan.Get4("Толщина листового металла", true, out valOut, out thickness); var columnNameClass = new ColumnNameEditPropTable(); if (configName == "00") { columnNameClass.ColumnNumber = number; } else { columnNameClass.ColumnNumber = "-" + configName; } columnNameClass.ColumnConfig = configName; columnNameClass.ColumnDescription = description; columnNameClass.ColumnThickness = thickness; columnNameClass.CodFb = codFb; columnNameClass.ColumnMatName = matName.Replace("$PRPSHEET:\"Толщина листового металла\"", thickness); columnRow.Add(columnNameClass); } } return(columnRow); }
public void TestLoadSWComponent(string modelName, byte[] pid) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); baseNode.Link.SWMainComponentPID = baseNode.Link.SWComponentPIDs[0]; Component2 component = Common.LoadSWComponent(doc, baseNode.Link.SWMainComponentPID); Assert.NotNull(component); SwApp.CloseAllDocuments(true); }
public void TestGetCountLink(string modelName, int expected) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); Link baseLink = baseNode.GetLink(); Assert.Equal(expected, Common.GetCount(baseLink)); SwApp.CloseAllDocuments(true); }
public static void Actualization(ModelDoc2 model, SwAddin _mSwAddin) { Component2 _swSelectedComponent = model.ConfigurationManager.ActiveConfiguration.GetRootComponent3(true); OleDbCommand cm; OleDbDataReader rd; OleDbConnection oleDb; if (!_mSwAddin.OpenModelDatabase(model, out oleDb)) return; cm = new OleDbCommand("SELECT * FROM faners ORDER BY FanerName ", oleDb); rd = cm.ExecuteReader(); List<Faner> faners = new List<Faner>(); while (rd.Read()) { if (rd["FanerType"] as string != null) { faners.Add(new Faner((string)rd["FanerName"], (string)rd["FanerType"], (string)rd["DecorGroup"])); } else { faners.Add(new Faner((string)rd["FanerName"], string.Empty, (string)rd["DecorGroup"])); } } rd.Close(); Feature feature; foreach (var faner in faners) { string suffix = faner.FanerName.Substring(faner.FanerName.Length - 2, 2); feature = FindEdge(_swSelectedComponent, faner.AxFanerName); if (feature != null) { if (feature.IsSuppressed()) { _mSwAddin.SetModelProperty(model, "Faner" + suffix, "", swCustomInfoType_e.swCustomInfoText, string.Empty, true); _mSwAddin.SetModelProperty(model, "colorFaner" + suffix, "", swCustomInfoType_e.swCustomInfoText, string.Empty, true); } else { string fieldValue = model.GetCustomInfoValue(string.Empty, "Faner" + suffix); if (fieldValue == string.Empty) { string msgText = "Для данной детали: " + model.GetPathName() + " кромка Faner" + suffix + " в модели не соответствует свойствам файла сборки. Данная кромка не будет импортирована в программу Покупки! Чтобы исправить эту ошибку используйте опцию \"MrDoors - Отделка кромки\""; MessageBox.Show(msgText, @"MrDoors", MessageBoxButtons.OK); } } } } }
public FrmEdge(SwAddin swAddin) { InitializeComponent(); _mSwAddin = swAddin; _swModel = (ModelDoc2)_mSwAddin.SwApp.ActiveDoc; _swSelMgr = (SelectionMgr)_swModel.SelectionManager; _swAsmDoc = (AssemblyDoc)_swModel; _swAsmDoc.NewSelectionNotify += NewSelection; pbEdge11.Image = null; pbEdge12.Image = null; pbEdge21.Image = null; pbEdge22.Image = null; NewSelection(); Show(); }
public AssemblyContext(string assemblyPath) { //var sw = Activator.GetObject(Type.GetTypeFromProgID("SldWorks.Application")) as SldWorks; //var sw = (SldWorks)System.Runtime.InteropServices.Marshal.GetActiveObject("SldWorks.Application"); sw = new SldWorks(); sw.Visible = true; workingFolder = Path.GetDirectoryName(assemblyPath); sw.SetCurrentWorkingDirectory(workingFolder); var filePath = assemblyPath; doc = sw.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref error, ref warning); drag = (DragOperator)((AssemblyDoc)doc).GetDragOperator(); math = (MathUtility)sw.GetMathUtility(); }
/// <summary> /// Constructs a new IJointAxis /// </summary> /// <param name="path">Path to this joint's storage</param> /// <param name="current">The joint that this axis is contained in</param> public IJointAxis(string path, Joint current) { this.swApp = RobotInfo.SwApp; this.modelDoc = RobotInfo.ModelDoc; this.swData = RobotInfo.SwData; this.path = path; this.owner = current; this.robot = RobotInfo.Robot; if (EffortLimit == 0) { this.EffortLimit = 1; } if (Axis != null) { CalcAxisVector(); } mathUtil = (MathUtility)swApp.GetMathUtility(); }
public FrmSetParameters(SwAddin swAddin) { InitializeComponent(); bitmap = Properties.Resources.Brush; tabMain.AutoSize = true; KeyDown += FormKeyDown; _mSwAddin = swAddin; _swModel = (ModelDoc2)_mSwAddin.SwApp.ActiveDoc; _swSelMgr = (SelectionMgr)_swModel.SelectionManager; _swAsmDoc = (AssemblyDoc)_swModel; _swAsmDoc.NewSelectionNotify += NewSelection; _swAsmDoc.AddItemNotify += AddNewItem; tabMain.Selected += TabMainTabSelected; tabMain.SelectedIndexChanged += TabMainSelectedIndexChanged; if (!Properties.Settings.Default.SetParentWindow) TopMost = true; Show(); NewSelection(); }
/// <summary> /// Creates a StorageModel for reading and writing data on the given Model /// </summary> /// <param name="model">Model to read and write data keys from</param> public StorageModel(ModelDoc2 model) { this.model = model; data = new Dictionary<string, LinkedList<IAttribute>>(); //storedDoubles = new Dictionary<string,List<double>>(); storedObjects = new Dictionary<string,object>(); //storedStrings = new Dictionary<string,List<string>>(); Feature feat = model.FirstFeature(); //Start scan of robot attribute's sub-features IAttribute attr; nextID = 0; int id; string path; int stopindex; LinkedList<IAttribute> newlist; while (feat != null) //Scan robot attribute's sub-features { if (feat.GetTypeName().Equals("Attribute")) { attr = (IAttribute)feat.GetSpecificFeature2(); if (attr.GetName().StartsWith("gsim")) { stopindex = attr.GetName().IndexOf("_"); id = Convert.ToInt32(attr.GetName().Substring(4, stopindex-4)); if (id >= nextID) nextID = id + 1; path = ((IParameter)attr.GetParameter("name")).GetStringValue(); if (!data.ContainsKey(path)) { newlist = new LinkedList<IAttribute>(); newlist.AddLast(attr); data.Add(path, newlist); } else data[path].AddLast(attr); } } feat = feat.GetNextFeature(); } }
//Selects the components of a link. Helps highlight when the associated node is selected from the tree public static void selectComponents(ModelDoc2 model, link Link, bool clearSelection, int mark = -1) { if (clearSelection) { model.ClearSelection2(true); } SelectionMgr manager = model.SelectionManager; SelectData data = manager.CreateSelectData(); data.Mark = mark; if (Link.SWComponent != null) { Link.SWComponent.Select4(true, data, false); } else { selectComponents(model, Link.SWcomponents, false); } foreach (link child in Link.Children) { selectComponents(model, child, false, mark); } }
public AssemblyExportForm(ISldWorks iSwApp, LinkNode node) { InitializeComponent(); swApp = iSwApp; BaseNode = node; ActiveSWModel = swApp.ActiveDoc; Exporter = new URDFExporter(iSwApp); AutoUpdatingForm = false; jointBoxes = new Control[] { textBox_joint_name, comboBox_axis, comboBox_joint_type, textBox_axis_x, textBox_axis_y, textBox_axis_z, textBox_joint_x, textBox_joint_y, textBox_joint_z, textBox_joint_pitch, textBox_joint_roll, textBox_joint_yaw, textBox_limit_lower, textBox_limit_upper, textBox_limit_effort, textBox_limit_velocity, textBox_damping, textBox_friction, textBox_calibration_falling, textBox_calibration_rising, textBox_soft_lower, textBox_soft_upper, textBox_k_position, textBox_k_velocity }; linkBoxes = new Control[] { textBox_inertial_origin_x, textBox_inertial_origin_y, textBox_inertial_origin_z, textBox_inertial_origin_roll, textBox_inertial_origin_pitch, textBox_inertial_origin_yaw, textBox_visual_origin_x, textBox_visual_origin_y, textBox_visual_origin_z, textBox_visual_origin_roll, textBox_visual_origin_pitch, textBox_visual_origin_yaw, textBox_collision_origin_x, textBox_collision_origin_y, textBox_collision_origin_z, textBox_collision_origin_roll, textBox_collision_origin_pitch, textBox_collision_origin_yaw, textBox_ixx, textBox_ixy, textBox_ixz, textBox_iyy, textBox_iyz, textBox_izz, textBox_mass, domainUpDown_red, domainUpDown_green, domainUpDown_blue, domainUpDown_alpha, comboBox_materials, textBox_texture }; saveConfigurationAttributeDef = iSwApp.DefineAttribute("URDF Export Configuration"); int Options = 0; saveConfigurationAttributeDef.AddParameter("data", (int)swParamType_e.swParamTypeString, 0, Options); saveConfigurationAttributeDef.AddParameter("name", (int)swParamType_e.swParamTypeString, 0, Options); saveConfigurationAttributeDef.AddParameter("date", (int)swParamType_e.swParamTypeString, 0, Options); saveConfigurationAttributeDef.AddParameter("exporterVersion", (int)swParamType_e.swParamTypeDouble, 1.0, Options); saveConfigurationAttributeDef.Register(); }
/// <summary> /// Creates a new joint /// </summary> /// <param name="path">Path to this joint in the StorageModel</param> /// <param name="owner">The Link that owns this joint (child Link in the joint)</param> public Joint(string path, Link parent, Link child) { this.swApp = RobotInfo.SwApp; this.asmDoc = RobotInfo.AssemDoc; this.modelDoc = RobotInfo.ModelDoc; this.swData = RobotInfo.SwData; this.path = path; this.robot = RobotInfo.Robot; this.Parent = parent; Parent.ChildJoints.Add(this); this.Child = child; this.Selected = false; this.Type = JointFactory.DefaultJointType; RobotInfo.WriteToLogFile("Getting Joint Specifics (Joint)"); jointSpecifics = JointFactory.GetSpecificJoint(Type,path,this); RobotInfo.WriteToLogFile("Successfully created Joint Specifics (Joint)"); if (swData.GetDouble(path) == 0) { swData.SetDouble(path, 1); } }
// This creates a Link from a Part ModelDoc. It basically just extracts the material properties and saves them to the appropriate fields. public link createLinkFromPartModel(ModelDoc2 swModel) { link Link = new link(); Link.name = swModel.GetTitle(); Link.isFixedFrame = false; Link.Visual = new visual(); Link.Inertial = new inertial(); Link.Collision = new collision(); //Get link properties from SolidWorks part IMassProperty swMass = swModel.Extension.CreateMassProperty(); Link.Inertial.Mass.value = swMass.Mass; double[] moment = swMass.GetMomentOfInertia((int)swMassPropertyMoment_e.swMassPropertyMomentAboutCenterOfMass); // returned as double with values [Lxx, Lxy, Lxz, Lyx, Lyy, Lyz, Lzx, Lzy, Lzz] Link.Inertial.Inertia.setMomentMatrix(moment); double[] centerOfMass = swMass.CenterOfMass; Link.Inertial.Origin.xyz = centerOfMass; Link.Inertial.Origin.rpy = new double[3] { 0, 0, 0 }; // Will this ever not be zeros? Link.Visual.Origin.xyz = new double[3] { 0, 0, 0 }; Link.Visual.Origin.rpy = new double[3] { 0, 0, 0 }; Link.Collision.Origin.xyz = new double[3] { 0, 0, 0 }; Link.Collision.Origin.rpy = new double[3] { 0, 0, 0 }; // [ R, G, B, Ambient, Diffuse, Specular, Shininess, Transparency, Emission ] double[] values = swModel.MaterialPropertyValues; Link.Visual.Material.Color.Red = values[0]; Link.Visual.Material.Color.Green = values[1]; Link.Visual.Material.Color.Blue = values[2]; Link.Visual.Material.Color.Alpha = 1.0 - values[7]; Link.Visual.Material.name = "material_" + Link.name; return Link; }
public PartEventHandler(ModelDoc2 modDoc, SwAddin addin) : base(modDoc, addin) { doc = (PartDoc)document; }
public DrawingEventHandler(ModelDoc2 modDoc, SwAddin addin) : base(modDoc, addin) { doc = (DrawingDoc)document; }
/// <summary> /// Creates a new robot editor proptery manager page that allows the user to select robot frame-of-reference objects. /// </summary> /// <param name="robot">Active robot model</param> /// <param name="document">Active assembly document</param> /// <param name="swApp">Solidworks application environment</param> public RobotPMPage(RobotModel robot, AssemblyDoc document, SldWorks swApp) { //Validate parameters if (robot == null) throw new ProgramErrorException("Tried to create a JointPMPage with a null robot model."); if (document == null) throw new ProgramErrorException("Tried to create a JointPMPage with a null assembly document."); if (swApp == null) throw new ProgramErrorException("Tried to create a JointPMPage with a null solidworks application interface."); //Initialize fields this.robot = robot; this.swApp = swApp; mathUtil = ((IMathUtility)swApp.GetMathUtility()); //AssemblyDoc inherits ModelDoc2 but the relationship dosn't carry through the COM interface //Having two fields prevents having to cast half of the time modelDoc = (ModelDoc2)document; assemblyDoc = document; //Setup the page, its controls and their visual layout SetupPage(); }
private void InitTableData() { md = (ModelDoc2)DrawingPropertySet.SwApp.ActiveDoc; mde = md.Extension; fracdisp = mde.GetUserPreferenceInteger((int)swUserPreferenceIntegerValue_e.swUnitsLinearDecimalDisplay, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified); //int den = mde.GetUserPreferenceInteger((int)swUserPreferenceIntegerValue_e.swUnitsLinearFractionDenominator, // (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified); decs = mde.GetUserPreferenceInteger((int)swUserPreferenceIntegerValue_e.swUnitsLinearDecimalPlaces, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified); decd = mde.GetUserPreferenceInteger((int)swUserPreferenceIntegerValue_e.swUnitsLinearDecimalDisplay, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified); try { mde.SetUserPreferenceInteger((int)swUserPreferenceIntegerValue_e.swUnitsLinearDecimalDisplay, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, (int)swFractionDisplay_e.swDECIMAL); mde.SetUserPreferenceInteger((int)swUserPreferenceIntegerValue_e.swUnitsLinearDecimalPlaces, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, 3); mde.SetUserPreferenceInteger((int)swUserPreferenceIntegerValue_e.swUnitsLinearDecimalDisplay, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, 3); md.ForceRebuild3(false); table = new swTableType.swTableType((DrawingPropertySet.SwApp.ActiveDoc as ModelDoc2), Redbrick.MasterHashes); } catch (NullReferenceException nre) { if (_swApp != null) { Redbrick.InsertBOM(_swApp); InitTableData(); } else { throw new NullReferenceException(@"No table found."); } } catch (Exception e) { RedbrickErr.ErrMsg em = new RedbrickErr.ErrMsg(e); em.ShowDialog(); Close(); } finally { // } }
public static void Create(ISldWorks app, ModelDoc2 mainModel) { string drawingTemplate = app.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateDrawing); ModelDoc2 designProject = app.NewDocument(drawingTemplate, (int)swDwgPaperSizes_e.swDwgPaperBsize, 0, 0); DrawingDoc designProjectDrawing = (DrawingDoc)designProject; int errors = 0; app.ActivateDoc2(designProject.GetTitle(), false, ref errors); designProjectDrawing.SetupSheet5("", (int)swDwgPaperSizes_e.swDwgPapersUserDefined, (int)swDwgTemplates_e.swDwgTemplateCustom, 1, 100, false, "a4 - iso.slddrt", 0.297, 0.21, "", true); var h = designProjectDrawing.CreateDrawViewFromModelView3(mainModel.GetPathName(), "*Изометрия", 0.1, 0.2, 0); List<OrderComponentData> orderData = new List<OrderComponentData>(); object[] allComponents = ((AssemblyDoc)mainModel).GetComponents(true); foreach (Component2 component in allComponents) { ModelDoc2 currentModel = component.GetModelDoc2(); string ip = GetCustomPropertyValue(currentModel, "IsProduct"); if (ip == "Yes") { orderData.Add( new OrderComponentData() { Article = GetCustomPropertyValue(currentModel, "Articul"), Name = GetCustomPropertyValue(currentModel, "Part_Name_spec"), Width = GetCustomPropertyValue(currentModel, "Size1_spec"), Depth = GetCustomPropertyValue(currentModel, "Size2_spec"), Height = GetCustomPropertyValue(currentModel, "Size3_spec"), Color1 = GetCustomPropertyValue(currentModel, "Color1"), Color2 = GetCustomPropertyValue(currentModel, "Color2"), Color3 = GetCustomPropertyValue(currentModel, "Color3"), Color4 = GetCustomPropertyValue(currentModel, "Color4"), Color5 = GetCustomPropertyValue(currentModel, "Color5"), Color6 = GetCustomPropertyValue(currentModel, "Color6"), Color7 = GetCustomPropertyValue(currentModel, "Color7") }); } } TableAnnotation table = designProjectDrawing.InsertTableAnnotation(0.01, 0.15, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft, orderData.Count + 1, 14); table.BorderLineWeight = 0; table.GridLineWeight = 0; #region Заполнение заголовков колонок таблицы table.set_Text(0, 0, "Поз."); table.set_Text(0, 1, "Артикул"); table.set_Text(0, 2, "Наименование изделия"); table.set_Text(0, 3, "Ширина"); table.set_Text(0, 4, "Глубина"); table.set_Text(0, 5, "Высота"); table.set_Text(0, 6, "Цвет 1"); table.set_Text(0, 7, "Цвет 2"); table.set_Text(0, 8, "Цвет 3"); table.set_Text(0, 9, "Цвет 4"); table.set_Text(0, 10, "Цвет 5"); table.set_Text(0, 11, "Цвет 6"); table.set_Text(0, 12, "Цвет 7"); table.set_Text(0, 13, "Кол-во"); #endregion int i = 1; foreach (OrderComponentData productData in orderData) { table.set_Text(i, 0, i.ToString()); table.set_Text(i, 1, productData.Article); table.set_Text(i, 2, productData.Name); table.set_Text(i, 3, productData.Width); table.set_Text(i, 4, productData.Depth); table.set_Text(i, 5, productData.Height); table.set_Text(i, 6, productData.Color1); table.set_Text(i, 7, productData.Color2); table.set_Text(i, 8, productData.Color3); table.set_Text(i, 9, productData.Color4); table.set_Text(i, 10, productData.Color5); table.set_Text(i, 11, productData.Color6); table.set_Text(i, 12, productData.Color7); i++; } table.SetColumnWidth(0, 0.013, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); table.SetColumnWidth(1, 0.025, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); table.SetColumnWidth(2, 0.07, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); for (int j = 3; j < 14; j++) { table.SetColumnWidth(j, 0.02, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); } designProject.ViewZoomtofit2(); }
public static string GetCustomPropertyValue(ModelDoc2 model, string propertyName) { CustomPropertyManager propertyManager = model.Extension.get_CustomPropertyManager(string.Empty); string value = string.Empty; string resolvedValue = string.Empty; propertyManager.Get4(propertyName, false, out value, out resolvedValue); return resolvedValue; }