/// <summary> /// Sets the status of a feature in the document /// </summary> /// <param name="name">Name of the feature</param> /// <param name="status">True of False if the feature should be active</param> /// <returns></returns> public bool SetFeatureStatus(string name, bool status) { var value = false; if (_document.DocumentType == DocumentTypeEnum.kPartDocumentObject) { PartDocument pdoc = _document as PartDocument; foreach (PartFeature p in pdoc.ComponentDefinition.Features) { if (p.Name == name) { p.Suppressed = status; value = true; break; } } } else if (_document.DocumentType == DocumentTypeEnum.kAssemblyDocumentObject) { AssemblyDocument adoc = _document as AssemblyDocument; foreach (PartFeature f in adoc.ComponentDefinition.Features) { if (f.Name == name) { f.Suppressed = status; value = true; break; } } } return(value); }
//create3Dline-------------------------------------------- private void button5_Click(object sender, EventArgs e) { // object[] HpCrd1 = new object[3]; // object[] HpCrd2 = new object[3]; try { sel = catia.ActiveDocument.Selection; HyShpPtCoord1 = (HybridShapeTypeLib.Point)sel.FindObject("CATIAHybridShapePoint"); //sel = catia.ActiveDocument.Selection; HyShpPtCoord2 = (HybridShapeTypeLib.Point)sel.FindObject("CATIAHybridShapePoint"); //HyShpPtCoord1.GetCoordinates(HpCrd1); //HyShpPtCoord1.GetCoordinates(HpCrd2); PartDocument prtDoc = (PartDocument)catia.ActiveDocument; Part prt = prtDoc.Part; HybridBody hbdy = prt.HybridBodies.Item(1); HybridShapeFactory hfac = (HybridShapeFactory)prt.HybridShapeFactory; INFITF.Reference ref1 = prt.CreateReferenceFromGeometry(HyShpPtCoord1); INFITF.Reference ref2 = prt.CreateReferenceFromGeometry(HyShpPtCoord2); HybridShapeTypeLib.Line lin = hfac.AddNewLinePtPt(ref1, ref2); hbdy.AppendHybridShape(lin); prt.Update(); } catch (Exception) { MessageBox.Show("선택된 정보가 없습니다."); return; } }
// create lines private void button1_Click(object sender, EventArgs e) { try { prtDoc = (PartDocument)catia.ActiveDocument; Part prt = prtDoc.Part; hbdy = prt.HybridBodies.Item(1); HybridShapeFactory hfac = (HybridShapeFactory)prt.HybridShapeFactory; //SelGS = (HybridBody)Sel.Item(1).Value; //INFITF.AnyObject aaa = Pts[0]; for (int i = 0; i <= (Pts.Count - 1); i++) { for (int j = i + 1; j < Pts.Count; j++) { HybridShapeTypeLib.Point pt1 = (HybridShapeTypeLib.Point)Pts.ElementAt(i); HybridShapeTypeLib.Point pt2 = (HybridShapeTypeLib.Point)Pts.ElementAt(j); INFITF.Reference ref1 = prt.CreateReferenceFromGeometry(pt1); INFITF.Reference ref2 = prt.CreateReferenceFromGeometry(pt2); HybridShapeTypeLib.Line lin = hfac.AddNewLinePtPt(ref1, ref2); hbdy.AppendHybridShape(lin); } } prt.Update(); } catch (Exception) { MessageBox.Show("선택된 정보가 없습니다."); return; } }
public Model GetProperty(PartDocument partDocument) { Box rangeBox = partDocument.ComponentDefinition.RangeBox; double x = Math.Round(Math.Abs(rangeBox.MaxPoint.X - rangeBox.MinPoint.X), 2); double y = Math.Round(Math.Abs(rangeBox.MaxPoint.Y - rangeBox.MinPoint.Y), 2); double z = Math.Round(Math.Abs(rangeBox.MaxPoint.Z - rangeBox.MinPoint.Z), 2); x.ToString().Replace(',', '.'); y.ToString().Replace(',', '.'); z.ToString().Replace(',', '.'); double[] arr = new double[] { x, y, z }; Array.Sort(arr); Array.Reverse(arr); var model = new Model { Length = arr[0], Height = arr[1], Width = arr[2], DetailName = partDocument.InternalName }; return(model); }
//由选择曲面获取iFeature特征 private void GetiFeature(ExtrudeFeature surfaceFeature, ref iFeature ifeature) { string ifeatureName; try { AttributeSets surfAttributeSets; surfAttributeSets = surfaceFeature.AttributeSets; AttributeSet surfAttibSet; surfAttibSet = surfaceFeature.AttributeSets["MyAttribSet"]; ifeatureName = (string)surfAttibSet["iFeatureName"].Value; } catch (System.Exception ex) { MessageBox.Show("获取属性集失败! " + ex.ToString()); return; } //获取iFeature PartDocument oPartDoc = (PartDocument)m_inventorApplication.ActiveDocument; iFeatures oiFeatures = oPartDoc.ComponentDefinition.Features.iFeatures; ifeature = oiFeatures[ifeatureName]; }
void UpdatePartData() { PartDocument doc = (PartDocument)m_inventorApplication.ActiveDocument; // calculate mass string material = doc.ComponentDefinition.Material.InternalName.Trim(); double mass = doc.ComponentDefinition.MassProperties.Mass; if (mass > 0) { // Create a profile item Hashtable parameters = new Hashtable(); parameters.Add("mass", mass.ToString()); parameters.Add("massUnit", "g"); parameters.Add("name", Guid.NewGuid().ToString()); parameters.Add("representation", "full"); Hashtable options = new Hashtable(); options.Add("returnUnit", "g"); ProfileItem item = m_AMEEProfile.CreateItem(DataMapping.Instance().Item(material), parameters, options); // Show the info window and shove data in it if (!m_summaryForm.Visible) { m_summaryForm.Show(new InventorWindow()); } m_summaryForm.UpdateData(item); } }
private void ButtonGetFaceNumber_Click(object sender, EventArgs e) { PartDocument doc = (PartDocument)ThisApplication.ActiveDocument; int n = doc.SelectSet.Count; if (n > 0) { Object ob = doc.SelectSet[1]; int edgeNumber = 0; int seeknumber = -1; foreach (SurfaceBody SurfBody in doc.ComponentDefinition.SurfaceBodies) { foreach (Face oEdge in SurfBody.Faces) { if (ob.Equals(oEdge)) { seeknumber = edgeNumber; } edgeNumber++; } } MessageBox.Show("" + seeknumber); } }
public static List <string> createSketchLavorazione(PartDocument oDoc, IDictionary <Face, List <Lavorazione> > lavorazione) { SheetMetalComponentDefinition oCompDef = (SheetMetalComponentDefinition)oDoc.ComponentDefinition; List <string> result = new List <string>(); int index = 1; foreach (var x in lavorazione) { Face oFace = x.Key; List <Lavorazione> lavList = x.Value; foreach (Lavorazione lav in lavList) { PlanarSketch oSketch = oCompDef.Sketches.Add(oFace, false); foreach (Edge oEdge in lav.oEdgeColl_) { oSketch.AddByProjectingEntity(oEdge); oSketch.Visible = false; } string nameSketch = lav.nameLav_ + "_" + index; oSketch.Name = nameSketch; result.Add(nameSketch); index++; } } return(result); }
public static void createCutLavorazione(PartDocument oDoc, List <string> nomeSketch) { SheetMetalComponentDefinition oCompDef = (SheetMetalComponentDefinition)oDoc.ComponentDefinition; foreach (string nameS in nomeSketch) { try { PlanarSketch oSketch = oCompDef.Sketches[nameS]; SheetMetalFeatures oSheetMetalFeatures = (SheetMetalFeatures)oCompDef.Features; Profile oProfile = oSketch.Profiles.AddForSolid(); CutDefinition oCutDefinition = oSheetMetalFeatures.CutFeatures.CreateCutDefinition(oProfile); //oCutDefinition.SetThroughAllExtent(PartFeatureExtentDirectionEnum.kNegativeExtentDirection); CutFeature oCutFeature = oSheetMetalFeatures.CutFeatures.Add(oCutDefinition); } catch { throw new Exception("Nome sketch non esiste: " + nameS); } } }
public static IDictionary <Face, List <Lavorazione> > detectLavorazioni(PartDocument oDoc) { IDictionary <Face, List <Lavorazione> > result = new Dictionary <Face, List <Lavorazione> >(); SheetMetalComponentDefinition oCompDef = (SheetMetalComponentDefinition)oDoc.ComponentDefinition; FaceCollection oFaceColl = oCompDef.Bends[1].FrontFaces[1].TangentiallyConnectedFaces; oFaceColl.Add(oCompDef.Bends[1].FrontFaces[1]); foreach (Face f in oFaceColl) { if (f.EdgeLoops.Count > 1) { List <Lavorazione> lavorazione = IdentificazioneEntita.main(f.EdgeLoops, iApp); if (lavorazione.Count > 0) { result.Add(f, lavorazione); } } } return(result); }
public static void createFillet(PartDocument oDoc) { SheetMetalComponentDefinition oCompDef = (SheetMetalComponentDefinition)oDoc.ComponentDefinition; SheetMetalFeatures sFeatures = (SheetMetalFeatures)oCompDef.Features; foreach (Edge oEdge in oCompDef.SurfaceBodies[1].ConcaveEdges) { int tmpCount = oCompDef.SurfaceBodies[1].ConcaveEdges.Count; coloroEntita(oDoc, 255, 0, 0, oEdge); try { EdgeCollection oBendEdges = iApp.TransientObjects.CreateEdgeCollection(); oBendEdges.Add(oEdge); BendDefinition oBendDef = sFeatures.BendFeatures.CreateBendDefinition(oBendEdges); BendFeature oBendFeature = sFeatures.BendFeatures.Add(oBendDef); //if (tmpCount != oCompDef.SurfaceBodies[1].ConcaveEdges.Count) //{ createFillet(oDoc); break; //} } catch { } } }
public static void coloroEntita(PartDocument oDoc, byte r, byte g, byte b, dynamic e) { HighlightSet oHS2 = oDoc.HighlightSets.Add(); oHS2.Color = iApp.TransientObjects.CreateColor(r, g, b); oHS2.AddItem(e); }
private void InitClientGraphics() { try { if (mInventorApp.ActiveDocumentType == DocumentTypeEnum.kAssemblyDocumentObject) { AssemblyDocument doc = mInventorApp.ActiveDocument as AssemblyDocument; if (null != doc) { mClientGraphics = doc.ComponentDefinition.ClientGraphicsCollection.Add("rubikcubeid"); } } else if (mInventorApp.ActiveDocumentType == DocumentTypeEnum.kPartDocumentObject) { PartDocument doc = mInventorApp.ActiveDocument as PartDocument; if (null != doc) { mClientGraphics = doc.ComponentDefinition.ClientGraphicsCollection.Add("rubikcubeid"); } } mClientGraphics.Selectable = GraphicsSelectabilityEnum.kAllGraphicsSelectable; } catch (Exception e) { } }
/* * static void Main(string[] args) * { * //GetExtrudeFeature(); * //ShowExtrudeFeature(); * //TestFunction(); * //SuppressOff(); * * //GetInventorApp(); * //AFunction(); * //EditDrawingDemensions(); * //防止闪退 * System.Console.ReadKey(); * } */ //拉伸特征、突出的特征 private static void GetExtrudeFeature() { Inventor.Application inventorApp = null; try { //获取一个Inventor的参考 inventorApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application"); } catch { MessageBox.Show("没有正常连接到Inventor"); return; } PartDocument partDoc = null; partDoc = (PartDocument)inventorApp.ActiveDocument; ExtrudeFeature extrude = null; //最后调用ExtrudeFeatures对象的Item属性,返回具有指定名称的ExtrudeFeature对象 extrude = partDoc.ComponentDefinition.Features.ExtrudeFeatures[1]; MessageBox.Show("Extrusion " + extrude.Name + " is suppressed:" + extrude.Suppressed); }
public override void OnPreSelect(object preSelectEntity, out bool doHighlight, ObjectCollection morePreSelectEntities, SelectionDeviceEnum selectionDevice, Point modelPosition, Point2d viewPosition, Inventor.View view) { doHighlight = false; if (preSelectEntity is Face) { Face preSelectFace = (Face)preSelectEntity; if (preSelectFace.SurfaceType == SurfaceTypeEnum.kCylinderSurface) { PartDocument oPartDoc = (PartDocument)m_inventorApplication.ActiveDocument; iFeatures oiFeatures = oPartDoc.ComponentDefinition.Features.iFeatures; foreach (iFeature oiFeature in oiFeatures) { Faces oFaces; oFaces = oiFeature.Faces; foreach (Face oFace in oFaces) { if (oFace == preSelectFace) { doHighlight = true; break; } } } } } }
public CutOp(Inventor.Document newDoc) { if (newDoc.DocumentType == DocumentTypeEnum.kAssemblyDocumentObject) { m_PartDoc = (PartDocument)newDoc.ActivatedObject; } if (newDoc.DocumentType == DocumentTypeEnum.kPartDocumentObject) { m_PartDoc = (PartDocument)newDoc; } if (m_PartDoc.SubType == "{9C464203-9BAE-11D3-8BAD-0060B0CE6BB4}") { smcd = (SheetMetalComponentDefinition)m_PartDoc.ComponentDefinition; } smf = (SheetMetalFeatures)smcd.Features; CutDefinition cd = smf.CutFeatures.CreateCutDefinition(selectFromSketch()); try { cd.SetCutAcrossBendsExtent("Толщина"); } catch (Exception) { cd.SetCutAcrossBendsExtent("Thickness"); } smf.CutFeatures.Add(cd); }
/// <summary> /// Updates the material for all parts /// </summary> public void updateMaterial() { AssemblyDocument assemblyDoc = (AssemblyDocument)invApp.ActiveDocument; DocumentsEnumerator allRefDocs = assemblyDoc.AllReferencedDocuments; // Find all part files and change the material foreach (Document oDoc in allRefDocs) { if (oDoc.DocumentType.Equals(DocumentTypeEnum.kPartDocumentObject)) { PartDocument partDoc = (PartDocument)oDoc; PartComponentDefinition partDef = partDoc.ComponentDefinition; // Try to set the material try { partDef.Material.Name = material; } catch { } finally { // Release objects partDoc = null; partDef = null; } } } // Release objects allRefDocs = null; assemblyDoc = null; }
private static void TestFunction() { Console.WriteLine("TestFunction"); Inventor.Application application = Marshal.GetActiveObject("Inventor.Application") as Inventor.Application; PartDocument partDoc = application.Documents.Add(DocumentTypeEnum.kPartDocumentObject, application.FileManager.GetTemplateFile(DocumentTypeEnum.kPartDocumentObject, SystemOfMeasureEnum.kDefaultSystemOfMeasure, DraftingStandardEnum.kDefault_DraftingStandard, null), true) as PartDocument; /* * PartComponentDefinition.Sketches Property * 二维草图的基本方法: * * Add 方法增加一个二维图纸 * Count 返回该集合里的草图个数 * Item 允许通过迭代的方式访问每一个成员 * * Delete 删除 * Edit 使草图处于编辑状态 * ExitEdit 草图退出编辑状态 * name 名称 * visible 可见性 */ ExtrudeFeatures extrudeFeatures = partDoc.ComponentDefinition.Features.ExtrudeFeatures; Console.WriteLine(extrudeFeatures.Count); for (int i = 0; i < extrudeFeatures.Count; i++) { Console.WriteLine(extrudeFeatures[i].Name); } Console.WriteLine("out"); }
internal CPartDocument( PartDocument document, InventorServer server) { m_Document = document; m_InventorServerObject = server; }
private static void ShowExtrudeFeature() { //Inventor.Application inventorApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application"); //PartDocument partDoc = (PartDocument)inventorApp.ActiveDocument; Inventor.Application inventorApp = null; try { //获取一个Inventor的参考 inventorApp = (Inventor.Application)Marshal.GetActiveObject("Inventor.Application"); } catch { MessageBox.Show("没有正常连接到Inventor"); return; } PartDocument partDoc = null; partDoc = (PartDocument)inventorApp.ActiveDocument; ExtrudeFeatures extrudeFeatures = partDoc.ComponentDefinition.Features.ExtrudeFeatures; for (int i = 0; i < extrudeFeatures.Count; i++) { Console.WriteLine(extrudeFeatures[1].Name); } }
public static void setSheetMetalDocument(PartDocument oDoc) { if (oDoc.SubType != "{9C464203-9BAE-11D3-8BAD-0060B0CE6BB4}") { oDoc.SubType = "{9C464203-9BAE-11D3-8BAD-0060B0CE6BB4}"; } }
public static string SubTypeString(this PartDocument partDocument) { if (partDocument == null) { throw new ArgumentNullException(nameof(partDocument)); } var subType = partDocument.SubType; switch (subType) { case PartDocumentId: return(PartDocumentName); case SheetMetalPartDocumentId: return(SheetMetalPartDocumentName); case GenericProxyPartDocumentId: return(GenericProxyPartDocumentName); case CompatibilityProxyPartDocumentId: return(CompatibilityProxyPartDocumentName); case CatalogProxyPartDocumentId: return(CatalogProxyPartDocumentName); case MoldedPartDocumentId: return(MoldedPartDocumentName); default: return(subType); } }
/// <summary> /// Updates the finish for all parts /// </summary> public void updateFinish() { AssemblyDocument assemblyDoc = (AssemblyDocument)invApp.ActiveDocument; DocumentsEnumerator allRefDocs = assemblyDoc.AllReferencedDocuments; // Find all part files and change the finish foreach (Document oDoc in allRefDocs) { if (oDoc.DocumentType.Equals(DocumentTypeEnum.kPartDocumentObject)) { PartDocument partDoc = (PartDocument)oDoc; PropertySet partCustomPropSet = partDoc.PropertySets["Inventor User Defined Properties"]; Property partProperty = partCustomPropSet["Finish"]; partProperty.Value = finish; // Release Objectsz partDoc = null; partCustomPropSet = null; partProperty = null; } } // Release objects allRefDocs = null; assemblyDoc = null; }
static void Main(string[] args) { /* * StreamReader sr = new StreamReader("point.txt"); * String line = ""; * List<Pt> ptlist = new List<Pt>(); * * while ((line = sr.ReadLine()) != null) * { * string[] token = line.Split(','); * int x = int.Parse(token[0]); * int y = int.Parse(token[1]); * int z = int.Parse(token[2]); * ptlist.Add(new Pt(x,y,z)); * } */ INFITF.Application catia; try { catia = (INFITF.Application)Marshal.GetActiveObject("CATIA.Application"); } catch (Exception) { catia = (INFITF.Application)Activator.CreateInstance(Type.GetTypeFromProgID("CATIA.Application")); } catia.Visible = true; PartDocument prtdoc = (PartDocument)catia.Documents.Add("Part"); Part prt = prtdoc.Part; HybridBodies hbdys = prt.HybridBodies; HybridBody hbdy = hbdys.Add(); HybridShapeFactory hsFac = (HybridShapeFactory)prt.HybridShapeFactory; try { StreamReader sr = new StreamReader("C:/Users/517-11/Desktop/saori/Automation/Catia-v5-Automation/RecapEx/point.txt"); String line = ""; //List<Pt> ptlist = new List<Pt>(); while ((line = sr.ReadLine()) != null) { string[] token = line.Split(','); int x = int.Parse(token[0]); int y = int.Parse(token[1]); int z = int.Parse(token[2]); // ptlist.Add(new Pt(x, y, z)); Point p = hsFac.AddNewPointCoord(x, y, z); hbdy.AppendHybridShape(p); } //Point p1 = hsFac.AddNewPointCoord(10, 60, 30); sr.Close(); prt.Update(); } catch (Exception e) { Console.WriteLine("파일io오류:" + e.Message); } }
private void Feature3(int x, int y) { PartDocument oPartDoc = (PartDocument)_invApp.ActiveDocument; oPartDoc.UnitsOfMeasure.LengthUnits = Inventor.UnitsTypeEnum.kMillimeterLengthUnits; PartComponentDefinition oCompDef = default(PartComponentDefinition); oCompDef = oPartDoc.ComponentDefinition; PlanarSketch oSketch = default(PlanarSketch); oSketch = oCompDef.Sketches.Add(oCompDef.WorkPlanes[3]); oSketch.SketchCircles.AddByCenterRadius(_invApp.TransientGeometry.CreatePoint2d(0, 0), 6); oSketch.SketchCircles.AddByCenterRadius(_invApp.TransientGeometry.CreatePoint2d(0, 0), 17.5); Profile oProfile = default(Profile); oProfile = oSketch.Profiles.AddForSolid(); ExtrudeDefinition oExtrudeDef = default(ExtrudeDefinition); oExtrudeDef = oCompDef.Features.ExtrudeFeatures.CreateExtrudeDefinition(oProfile, Inventor.PartFeatureOperationEnum.kJoinOperation); oExtrudeDef.SetDistanceExtent(3, Inventor.PartFeatureExtentDirectionEnum.kPositiveExtentDirection); ExtrudeFeature oExtrude = default(ExtrudeFeature); oExtrude = oCompDef.Features.ExtrudeFeatures.Add(oExtrudeDef); }
public Boolean ErzeugePart() { Documents catDocuments = hsp_catiaApp.Documents; hsp_catiaPart = (PartDocument)catDocuments.Add("Part") as MECMOD.PartDocument; return(true); }
private void ExtrudeSketch(int x, int y) { //PartDocument oPartDoc = default(PartDocument); //oPartDoc = (PartDocument)_invApp.Documents.Add(Inventor.DocumentTypeEnum.kPartDocumentObject,_invApp.FileManager.GetTemplateFile(Inventor.DocumentTypeEnum.kPartDocumentObject)); PartDocument oPartDoc = (PartDocument)_invApp.ActiveDocument; PartComponentDefinition oCompDef = default(PartComponentDefinition); oCompDef = oPartDoc.ComponentDefinition; PlanarSketch oSketch = default(PlanarSketch); oSketch = oCompDef.Sketches.Add(oCompDef.WorkPlanes[1]); oSketch.SketchLines.AddAsTwoPointRectangle(_invApp.TransientGeometry.CreatePoint2d(-x, -y), _invApp.TransientGeometry.CreatePoint2d(x, y)); Profile oProfile = default(Profile); oProfile = oSketch.Profiles.AddForSolid(); ExtrudeDefinition oExtrudeDef = default(ExtrudeDefinition); oExtrudeDef = oCompDef.Features.ExtrudeFeatures.CreateExtrudeDefinition(oProfile, Inventor.PartFeatureOperationEnum.kJoinOperation); oExtrudeDef.SetDistanceExtent(5, Inventor.PartFeatureExtentDirectionEnum.kSymmetricExtentDirection); ExtrudeFeature oExtrude = default(ExtrudeFeature); oExtrude = oCompDef.Features.ExtrudeFeatures.Add(oExtrudeDef); }
private Box GetSceneBox() { if (null == mSceneBox) { PartDocument partDoc = mInventorApp.ActiveDocument as PartDocument; if (null != partDoc) { ClientGraphics clientGraphics = null; try { clientGraphics = partDoc.ComponentDefinition.ClientGraphicsCollection["rubikcubeid"]; } catch (Exception) { } if (null != clientGraphics) { mSceneBox = mInventorApp.TransientGeometry.CreateBox(); foreach (GraphicsNode node in clientGraphics) { mSceneBox.Extend(node.RangeBox.MinPoint); mSceneBox.Extend(node.RangeBox.MaxPoint); } } } } return(mSceneBox); }
/// <summary> /// Pass a string that is the name of the parameter and the value of the parameter will be returned as a string /// </summary> /// <param name="documentToWork"></param> /// <param name="nameOfParameterToGet"></param> /// <returns></returns> public static List <string> GetParameterNames(this Document documentToWork) { Parameters listOfParameters; if (documentToWork.DocumentType == DocumentTypeEnum.kAssemblyDocumentObject) { AssemblyDocument identifiedAssemblyDocument = (AssemblyDocument)documentToWork; listOfParameters = identifiedAssemblyDocument.ComponentDefinition.Parameters; } else if (documentToWork.DocumentType == DocumentTypeEnum.kPartDocumentObject) { PartDocument identifiedPartDocument = (PartDocument)documentToWork; listOfParameters = identifiedPartDocument.ComponentDefinition.Parameters; } else { throw new Exception("Unknown type of document passed to GetParameterNames"); } var returnList = new List <string>(); foreach (Parameter parameter in listOfParameters) { returnList.Add(parameter.Name); } return(returnList); }
private void buttonTest_Click(object sender, EventArgs e) { try { //CATIA=(INFITF.Application)Marshal.GetActiveObject("CATIA.Application"); CATIA = (INFITF.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Catia.Application"); } catch { Type oType = System.Type.GetTypeFromProgID("CATIA.Application"); CATIA = (INFITF.Application)Activator.CreateInstance(oType); CATIA.Visible = true; } Document doc = CATIA.ActiveDocument; PartDocument partDoc = (PartDocument)doc; Part part = partDoc.Part; string sAlias = "CAAIATestInterfaceVB"; //InstanceFactory fact = (InstanceFactory)part.GetCustomerFactory(ref sAlias); TestIDLFrm.CAAIATestInterfaceVB testIntf = (TestIDLFrm.CAAIATestInterfaceVB)(part.GetCustomerFactory(ref sAlias)); //HybridShapeFactory hsFactory = (HybridShapeFactory)part.GetCustomerFactory(ref sAlias); //try //{ // testIntf.CreateObject(); //} //catch (System.Exception ex) //{ //} string isName = ""; string osName = ""; osName = testIntf.TestFunction(ref isName); }
public Part(PartDocument partDocument) { if (partDocument == null) throw new ArgumentNullException(nameof(partDocument)); Document = partDocument; SetCustomPropertyFormat(CustomPropertyPrecisionEnum.kZeroDecimalPlacePrecision, showTrailingZeros: false); }
/// <summary> /// Инициализация приложения /// </summary> public void Initialization(Application InventorApplication) { if (InventorApplication == null) throw new AccessingNullException(); // В открытом приложении создаем метрическуюсборку _partDoc = (PartDocument)InventorApplication.Documents.Add (DocumentTypeEnum.kPartDocumentObject, InventorApplication.FileManager.GetTemplateFile (DocumentTypeEnum.kPartDocumentObject, SystemOfMeasureEnum.kMetricSystemOfMeasure)); //Описание документа _partDef = _partDoc.ComponentDefinition; //инициализация метода геометрии _transGeometry = InventorApplication.TransientGeometry; }
internal string SaveSurfaceAndFixedPoints(ref List<double[]> FixedPoints, ref double[] oPlane) { string StlPath= System.IO.Path.GetTempPath() + "STLFileBlankCalculator"; ; oPartDoc = (PartDocument)CATIA.ActiveDocument; oSel = oPartDoc.Selection; oSpa = (SPAWorkbench)oPartDoc.GetWorkbench("SPAWorkbench"); FixedPoints = new List<double[]>(); oSel.Clear(); oSel.Add(SelectSurface("Selecione qual a superficie que pretende planificar. Esc para sair.")); oSel.Copy(); oSel.Clear(); PartDocument NewPart = (PartDocument)CATIA.Documents.Add("Part"); NewPart.Selection.Clear(); NewPart.Selection.Add(NewPart.Part); NewPart.Selection.PasteSpecial("CATPrtResultWithOutLink"); if (System.IO.File.Exists(StlPath + ".stl")) { System.IO.File.Delete(StlPath + ".stl"); } NewPart.Selection.Clear(); NewPart.Part.Update(); CATIA.DisplayFileAlerts = false; NewPart.ExportData(StlPath, "stl"); NewPart.Close(); CATIA.DisplayFileAlerts = true; object[] Vec = new object[3]; oSel.Clear(); Reference Ref1 = SelectPoint("Selecione o conjunto de pontos fixos. Esc para sair."); oSel.Clear(); if (Ref1 == null) Environment.Exit(0); oSpa.GetMeasurable(Ref1).GetPoint(Vec); FixedPoints.Add(new double[] { (double)Vec[0], (double)Vec[1], (double)Vec[2] }); do { Ref1 = SelectPoint("Selecione o conjunto de pontos fixos (" + FixedPoints.Count + " selecionados). Esc para terminar."); oSel.Clear(); if (Ref1 == null) break; oSpa.GetMeasurable(Ref1).GetPoint(Vec); FixedPoints.Add(new double[] { (double)Vec[0], (double)Vec[1], (double)Vec[2] }); } while (true); if(FixedPoints.Count==0) Environment.Exit(0); oSel.Clear(); oPartDoc.Part.Update(); System.Windows.Forms.Application.DoEvents(); System.Threading.Thread.Sleep(500); Vec = new object[9]; Reference Ref2 = SelectPlane("Selecione qual o plano do planificado. Esc para terminar."); oSel.Clear(); oSpa.GetMeasurable(Ref2).GetPlane(Vec); oPlane = new double[] { (double)Vec[0], (double)Vec[1], (double)Vec[2], (double)Vec[3], (double)Vec[4], (double)Vec[5], (double)Vec[6], (double)Vec[7], (double)Vec[8] }; return StlPath + ".stl"; }
/// <summary> /// Returns the unit quantity of a specified part. /// </summary> /// <param name="assemblyDocument"> /// The <see cref="AssemblyDocument"/> instance that this extension method affects.</param> /// <param name="part">The part.</param> /// <param name="displayWarnings">A value which indicates wheter to display warnings, if they occur.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> or <paramref name="part"/>is <c>null</c>.</exception> public static int GetPartQuantity(this AssemblyDocument assembly, PartDocument part, bool displayWarnings) { if (assembly == null) throw new ArgumentNullException(nameof(assembly)); if (part == null) throw new ArgumentNullException(nameof(part)); var bom = assembly.ComponentDefinition.BOM; if (bom == null) return 0; if (displayWarnings && bom.RequiresUpdate) AddIn.ShowWarningMessageBox( AssemblyInfo.Name, $"The BOM of assembly '{assembly.DisplayName}' requires an update. " + "Quantities displayed in the generated drawing might be incorrect." ); try { bom.PartsOnlyViewEnabled = true; } catch (ArgumentException) { return 0; } BOMView partsOnlyView; if (bom.BOMViews.TryGetValue("Parts Only", out partsOnlyView)) foreach (BOMRow row in partsOnlyView.BOMRows) { if (row.ComponentDefinitions.Count == 0) continue; var componentDefinition = row.PrimaryComponentDefinition(); if (componentDefinition == null) continue; var document = componentDefinition.Document as Document; if (document == null) continue; if (document.FullFileName == part.FullFileName) return row.ItemQuantity; } return 0; }
private void CreateShaft3dmodel(object sender, EventArgs e) { if (listViewShaftElements.Items.Count > 0) { if ((!ModelCreated) & (HeightOfNeighbourElementsIsDifferent())) { PlanarSketch oSketch = default(PlanarSketch); SketchPoints oSkPnts = default(SketchPoints); Object actObj = ThisApplication.ActiveEditObject; oSketch = (PlanarSketch)actObj; oSkPnts = oSketch.SketchPoints; oTransGeom = ThisApplication.TransientGeometry; partDoc = (Inventor.PartDocument)ThisApplication.ActiveDocument; oPartCompDef = partDoc.ComponentDefinition; int TotalLenght2 = 0; foreach (ListViewItem eachItem in listViewShaftElements.Items) { PartOfShaft POShaft = new PartOfShaft(); POShaft.PartHeight = Convert.ToInt32(eachItem.SubItems[1].Text); POShaft.PartWidth = Convert.ToInt32(eachItem.SubItems[2].Text); POShaft.CRectangle(POShaft.PartWidth, POShaft.PartHeight, TotalLenght2); TotalLenght2 = TotalLenght2 + POShaft.PartWidth; tbLenghtOfShaft.Text = Convert.ToString(TotalLenght2); } // Создание центральной оси для будущего вращения прямоугольников вокруг нее. Point2d CentralLine_StartPoint = oTransGeom.CreatePoint2d(0, 0); Point2d CentralLine_EndPoint = oTransGeom.CreatePoint2d(TotalLenght2, 0); SketchLine CentralLineForRevolveAround = default(SketchLine); CentralLineForRevolveAround = oSketch.SketchLines.AddByTwoPoints(CentralLine_StartPoint, CentralLine_EndPoint); // Вращение. oProfile0 = oSketch.Profiles.AddForSolid(); RevolveFeature oRevFeature = default(RevolveFeature); oRevFeature = partDoc.ComponentDefinition.Features.RevolveFeatures.AddFull(oProfile0, CentralLineForRevolveAround, PartFeatureOperationEnum.kNewBodyOperation); // Добавление фасок и кромок. int StartPoint_X = 0, EndPoint_X = 0; double MiddlePoint_X1 = 0, MiddlePoint_X2 = 0; double SizeOfTypeStart = 0, SizeOfTypeEnd = 0; double AngleStart, AngleEnd, SizeOfTypeEnd1, SizeOfTypeEnd2, SizeOfTypeStart1, SizeOfTypeStart2; foreach (ListViewItem eachItem in listViewShaftElements.Items) { Point oPointStart = default(Point); oPointStart = oTransGeom.CreatePoint(StartPoint_X, Convert.ToInt32(eachItem.SubItems[1].Text)); MiddlePoint_X1 = StartPoint_X + Convert.ToDouble(eachItem.SubItems[2].Text) / 2 - 0.02; MiddlePoint_X2 = StartPoint_X + Convert.ToDouble(eachItem.SubItems[2].Text) / 2 + 0.02; StartPoint_X = StartPoint_X + Convert.ToInt32(eachItem.SubItems[2].Text); Point oPointEnd = default(Point); EndPoint_X = StartPoint_X; oPointEnd = oTransGeom.CreatePoint(EndPoint_X, Convert.ToInt32(eachItem.SubItems[1].Text)); Point oPointMiddle = default(Point); oPointMiddle = oTransGeom.CreatePoint(MiddlePoint_X1, Convert.ToInt32(eachItem.SubItems[1].Text)); Face objFaceMiddle = (Face)partDoc.ComponentDefinition.SurfaceBodies[1].LocateUsingPoint(ObjectTypeEnum.kFaceObject, oPointMiddle, 0.01); Object objStart = partDoc.ComponentDefinition.SurfaceBodies[1].LocateUsingPoint(ObjectTypeEnum.kEdgeObject, oPointStart, 0.01); partDoc.SelectSet.Select(objStart); // Определение коллекции начальных углов. EdgeCollection oEdgesStart = default(EdgeCollection); oEdgesStart = ThisApplication.TransientObjects.CreateEdgeCollection(); oEdgesStart.Add(objStart); try { switch (eachItem.SubItems[3].Text) { case "Standart": partDoc.SelectSet.Clear(); break; case "Fillet": SizeOfTypeStart = Convert.ToDouble(eachItem.SubItems[4].Text); FilletFeature oFilletStart = default(FilletFeature); oFilletStart = oPartCompDef.Features.FilletFeatures.AddSimple(oEdgesStart, SizeOfTypeStart); break; case "Chamfer (Distance)": SizeOfTypeStart = Convert.ToDouble(eachItem.SubItems[4].Text); ChamferFeature oChamferStart_D = default(ChamferFeature); oChamferStart_D = oPartCompDef.Features.ChamferFeatures.AddUsingDistance(oEdgesStart, SizeOfTypeStart); break; case "Chamfer (Distance And Angle)": SizeOfTypeStart = Convert.ToDouble(eachItem.SubItems[4].Text); AngleStart = Convert.ToDouble(eachItem.SubItems[6].Text); ChamferFeature oChamferStart_DaA = default(ChamferFeature); oChamferStart_DaA = oPartCompDef.Features.ChamferFeatures.AddUsingDistanceAndAngle(oEdgesStart, objFaceMiddle, SizeOfTypeStart, AngleStart); break; case "Chamfer (Two Distances)": SizeOfTypeStart1 = Convert.ToDouble(eachItem.SubItems[4].Text); SizeOfTypeStart2 = Convert.ToDouble(eachItem.SubItems[5].Text); ChamferFeature oChamferStart_DD = default(ChamferFeature); oChamferStart_DD = oPartCompDef.Features.ChamferFeatures.AddUsingTwoDistances(oEdgesStart, objFaceMiddle, SizeOfTypeStart1, SizeOfTypeStart2); break; } } catch { MessageBox.Show(eachItem.SubItems[3].Text + " " + eachItem.SubItems[4].Text + " " + eachItem.SubItems[5].Text + " " + eachItem.SubItems[6].Text); } Point oPointMiddle2 = default(Point); oPointMiddle2 = oTransGeom.CreatePoint(MiddlePoint_X2, Convert.ToInt32(eachItem.SubItems[1].Text)); Face objFaceMiddle2 = (Face)partDoc.ComponentDefinition.SurfaceBodies[1].LocateUsingPoint(ObjectTypeEnum.kFaceObject, oPointMiddle2, 0.01); Object objEnd = partDoc.ComponentDefinition.SurfaceBodies[1].LocateUsingPoint(ObjectTypeEnum.kEdgeObject, oPointEnd, 0.01); partDoc.SelectSet.Select(objEnd); // Определение коллекции конечных углов. EdgeCollection oEdgesEnd = default(EdgeCollection); oEdgesEnd = ThisApplication.TransientObjects.CreateEdgeCollection(); oEdgesEnd.Add(objEnd); switch (eachItem.SubItems[7].Text) { case "Standart": partDoc.SelectSet.Clear(); break; case "Fillet": SizeOfTypeEnd = Convert.ToDouble(eachItem.SubItems[8].Text); FilletFeature oFilletEnd = default(FilletFeature); oFilletEnd = oPartCompDef.Features.FilletFeatures.AddSimple(oEdgesEnd, SizeOfTypeEnd); break; case "Chamfer (Distance)": SizeOfTypeEnd = Convert.ToDouble(eachItem.SubItems[8].Text); ChamferFeature oChamferEnd_D = default(ChamferFeature); oChamferEnd_D = oPartCompDef.Features.ChamferFeatures.AddUsingDistance(oEdgesEnd, SizeOfTypeEnd); break; case "Chamfer (Distance And Angle)": SizeOfTypeEnd = Convert.ToDouble(eachItem.SubItems[8].Text); AngleEnd = Convert.ToDouble(eachItem.SubItems[10].Text); ChamferFeature oChamferEnd_DaA = default(ChamferFeature); oChamferEnd_DaA = oPartCompDef.Features.ChamferFeatures.AddUsingDistanceAndAngle(oEdgesEnd, objFaceMiddle2, SizeOfTypeEnd, AngleEnd); break; case "Chamfer (Two Distances)": SizeOfTypeEnd1 = Convert.ToDouble(eachItem.SubItems[8].Text); SizeOfTypeEnd2 = Convert.ToDouble(eachItem.SubItems[9].Text); ChamferFeature oChamferEnd_DD = default(ChamferFeature); oChamferEnd_DD = oPartCompDef.Features.ChamferFeatures.AddUsingTwoDistances(oEdgesEnd, objFaceMiddle2, SizeOfTypeEnd1, SizeOfTypeEnd2); break; } } ThisApplication.ActiveView.GoHome(); ModelCreated = true; } else if (ModelCreated) { MessageBox.Show("The 3d model was already created!"); } } }
public static void Main(string[] args) { Application CATIA = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Catia.Application"); oPartDocument = (PartDocument)CATIA.Documents.Add ( "Part" ); oPart = oPartDocument.Part; oPartBody = oPart.MainBody; oPlaneYZ = oPart.CreateReferenceFromGeometry( oPart.OriginElements.PlaneYZ ); //CATIA.ActiveWindow.ActiveViewer.RenderingMode = 1; //msgbox "Create Five Bearings" CreatePatternBearing(); oPart.Update(); CATIA.ActiveWindow.ActiveViewer.Reframe(); //msgbox "Create First Cam Set" CreateCamSet (0); oPart.Update(); CATIA.ActiveWindow.ActiveViewer.Reframe(); //msgbox "Create Second Cam Set" CreateCamSet (90); oPart.Update(); CATIA.ActiveWindow.ActiveViewer.Reframe(); //msgbox "Create Third Cam Set" CreateCamSet (180); oPart.Update(); CATIA.ActiveWindow.ActiveViewer.Reframe(); //msgbox "Create Fourth Cam Set" CreateCamSet (270); oPart.Update(); CATIA.ActiveWindow.ActiveViewer.Reframe(); //msgbox "Create Driving Wheel" CreateCylinder (iPinLength/2, iBearingDiam ); oPart.Update(); CATIA.ActiveWindow.ActiveViewer.Reframe(); //msgbox "This is the macro end" }
/// <summary> /// Returns the unit quantity of a specified part. /// </summary> /// <param name="assemblyDocument"> /// The <see cref="AssemblyDocument"/> instance that this extension method affects.</param> /// <param name="part">The part.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="assembly"/> or <paramref name="part"/>is <c>null</c>.</exception> public static int GetPartQuantity(this AssemblyDocument assembly, PartDocument part) { return GetPartQuantity(assembly, part, displayWarnings: false); }