private void button1_Click(object sender, EventArgs e) { double r1 = Convert.ToDouble(textBox1.Text) / 1e3; double r2 = Convert.ToDouble(textBox2.Text) / 1e3; double h = Convert.ToDouble(textBox3.Text) / 1e3; SldWorks sw = new SldWorks(); sw.Visible = true; PartDoc Part = sw.NewPart(); ModelDoc2 Model = sw.ActiveDoc; Model.InsertSketch2(true); Model.SelectByID("Спереди", "PLANE", 0, 0, 0); // Выделяем плоскость на которой будем рисовать Model.InsertSketch2(true); // Добавляем эскиз Model.CreateCircleByRadius2(0, 0, 0, r1); // рисуем окружность 1 Model.CreateCircleByRadius2(0, 0, 0, r2); // рисуем окружность 2 Model.FeatureBoss2(true, false, false, 0, 0, h, 0, true, false, true, false, 0, 0, false, false, false, false); // Бобышка - вытянуть /*Model.CreateEllipse2(0, 0, 0, 1, 0, 0, 0, 2, 0); * Model.FeatureBoss2(true, false, false, 0, 0, 1, 0, true, false, true, false, 0.5, 0, false, false, false, false);*/ }
public override void CreatePart() { swApp = SolidWorksSingleton.GetApplication(); DocumentManager.CreateNewPartDoc(); swModel = (ModelDoc2)swApp.ActiveDoc; swFeature = swModel.FeatureByPositionReverse(3); swFeature.Name = "Front"; swModel.Extension.SelectByID2("Front", "PLANE", 0, 0, 0, false, 0, null, 0); swModel.InsertSketch2(true); swModel.CreateCircleByRadius2(0, 0, 0, InsideDiameter / 2); swModel.CreateCircleByRadius2(0, 0, 0, OutsideDiameter / 2); swModel.InsertSketch2(true); swFeature = swModel.FeatureManager.FeatureExtrusion3(true, false, false, 0, 0, Lenght, 0, false, false, false, false, 0, 0, false, false, false, false, false, false, false, 0, 0, false); BasicOpertations.ChangeEntityName("FACE", MateOutsideFace, OutsideDiameter / 2, 0, Lenght / 2); double dim = (OutsideDiameter - InsideDiameter) / 4; BasicOpertations.ChangeEntityName("FACE", MateBase, (InsideDiameter / 2) + dim, 0, 0); DocumentManager.Save(TargetFolder, FileName, DocumentManager.sw_DocType.part); }
// Open "Edit Sketch" and make sketch Normal-To (ctrl+8 shortcut) given the Feature private bool OpenSketchNormalToByName(string sketchName) { // Exit out of any opened sketches if (currentModel.SketchManager.ActiveSketch != null) { currentModel.InsertSketch2(true); } ModelDocExtension swModelDocExt = default(ModelDocExtension); swModelDocExt = currentModel.Extension; bool selected = swModelDocExt.SelectByID2(sketchName, "SKETCH", 0, 0, 0, false, 0, null, 0); if (!selected) { ShowNonFatalError("Failed to select sketch '" + sketchName + "'"); return(false); } // Open sketch for editing ("Edit Sketch" in Solidworks UI) currentModel.EditSketchOrSingleSketchFeature(); // Run the 'Normal-To' view command if (RunNormalToSketchCommand() != 0) { return(false); } return(true); }
// (UNUSED, for future reference) Loops through all sketches in a given ModelDoc2 model public void iterate_each_sketch_in_model(ModelDoc2 thisModel) { Console.WriteLine("Iterating through all sketches in this model..."); if (thisModel == null) { Console.WriteLine("** Error: thisModel is NULL! Something's wrong..."); } Feature currentFeature = default(Feature); int numParentFeatures = 0; int numSketches = 0; currentFeature = thisModel.IFirstFeature(); List <Feature> listOfSketches = new List <Feature>(); // Loop through all features in 'thisModel' while (currentFeature != null) { numParentFeatures++; if (currentFeature.GetTypeName2() == "ProfileFeature") // If child is type Sketch { // Gather properties of sketch Console.WriteLine("Iterating through parentFeature" + numParentFeatures + " ('" + currentFeature.Name + "') in this model..."); GetConstrainedStatus(currentFeature); // Clear all previous selections thisModel.ClearSelection2(true); // Select the current sketch (we verified this feature is a sketch) if (currentFeature.Select2(false, 0)) { Console.WriteLine("Successfully selected Sketch ('" + currentFeature.Name + "')"); listOfSketches.Add(currentFeature); } else { Console.WriteLine(" ** ERROR: Failed to select Sketch ('" + currentFeature.Name + "')"); break; } // Edit the (previously selected) sketch Console.WriteLine(" Editing sketch......"); thisModel.EditSketchOrSingleSketchFeature(); // Run the 'Normal-To' view command RunNormalToSketchCommand(); // Exit out of "Edit Sketch" and rebuild thisModel.InsertSketch2(true); } currentFeature = currentFeature.GetNextFeature(); if (currentFeature == null) { Console.WriteLine("Failed to get next feature! (GetNextFeature() is NULL)"); } } Console.WriteLine("Got " + numSketches + " sketches from this model"); }
// Opens a Solidworks part, given a part TreeNode private bool OpenPartFromNode(TreeNode partNode) { // Gets the current part's name (if open), to break if new part is already open ModelDoc2 currentPart = default(ModelDoc2); currentPart = swApp.IActiveDoc2; string currentPartName; if (currentPart == null) { currentPartName = ""; } else { currentPartName = currentPart.GetTitle(); } // Get custom PartNodeInfo object from this node PartNodeInfo pNodeInfo = (PartNodeInfo)partNode.Tag; string fileName = pNodeInfo.FileName; // Exit if same part is already open if (fileName == currentPartName) { Console.WriteLine("Part is already opened. Skipping PartOpen."); currentModel = currentPart; // Exit out of any opened sketches if (currentModel.SketchManager.ActiveSketch != null) { currentModel.InsertSketch2(true); } return(true); } // Close current part and open new part Console.WriteLine("Opening student {0}'s part file: '{1}'.", pNodeInfo.Student.Name, fileName); CloseCurrentPart(); ModelDoc2 newPart = default(ModelDoc2); newPart = GetSolidworksModelFromFile(pNodeInfo.FilePath); if (newPart == null) // Opens up the new part { Console.WriteLine("Failed to open part file '{0}'", fileName); return(false); } currentModel = newPart; Console.WriteLine("Opened part successfully."); ExpandAllSolidworksFeaturesInTree(newPart); return(true); }
private void b_create_Click(object sender, EventArgs e) { // Abfrage der Eingabe aus allen Textboxen. // TryParse probiert den String in eine double-Variable zu konvertieren. // Liefert true zurück, wenn String konvertiert werden konnte. // Konvertierter Wert wird in Variable kopiert durch das Wort out. if (double.TryParse(tb_breite.Text, out breite) == false || double.TryParse(tb_laenge.Text, out laenge) == false || double.TryParse(tb_hoehe.Text, out hoehe) == false) // || //double.TryParse(tb_radius.Text, out radius) == false) { MessageBox.Show("Fehlerhafte Eingabe!"); return; } // Werte müssen von mm in m konvertiert werden. breite /= 1000.0; laenge /= 1000.0; hoehe /= 1000.0; radius /= 1000.0; // Anlegen eines neuen Bauteiles. ModelDoc2 swModel = swApp.NewPart(); // Ebene oben wird selektiert und eine Skizze wird eingefügt. swModel.Extension.SelectByID("Ebene oben", "PLANE", 0, 0, 0, false, 1, null); swModel.InsertSketch2(true); // Skizze wird in Feature konvertiert, damit diese benannt werden kann. Sketch swSketch = swModel.GetActiveSketch2(); Feature swFeat = (Feature)swSketch; swFeat.Name = "Grundflaeche"; swModel.SketchRectangle(0, 0, 0, breite, laenge, 0, true); Feature swFeat2 = swModel.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, hoehe, 0, false, false, false, false, 0, 0, false, false, false, false, true, true, true, 0, 0, true); swFeat2.Name = "Quader"; swModel.SaveAsSilent("C:\\temp\\Quader_L_" + tb_laenge.Text + "_B_" + tb_breite.Text + "_H_" + tb_hoehe.Text + ".SLDPRT", true); }
public void OnClose(int reason) { //This function must contain code, even if it does nothing, to prevent the //.NET runtime environment from doing garbage collection at the wrong time. int IndentSize; IndentSize = System.Diagnostics.Debug.IndentSize; System.Diagnostics.Debug.WriteLine(IndentSize); if (reason == (int)swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_Okay) { string partTemplate = iSwApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); if ((partTemplate != null) && (partTemplate != "")) { swModel = (ModelDoc2)iSwApp.NewDocument(partTemplate, (int)swDwgPaperSizes_e.swDwgPaperA2size, 0.0, 0.0); swModel.InsertSketch2(true); double x = this.activePage.CubeLength / ValueConst.factor; double y = this.activePage.CubeWidth / ValueConst.factor; double z = this.activePage.CubeHeight / ValueConst.factor; swModel.SketchRectangle(0, 0, 0, x, y, 0, false); //Extrude the sketch IFeatureManager featMan = swModel.FeatureManager; Feature valuebody = featMan.FeatureExtrusion(true, false, false, (int)swEndConditions_e.swEndCondBlind, (int)swEndConditions_e.swEndCondBlind, z, 0.0, false, false, false, false, 0.0, 0.0, false, false, false, false, true, false, false); //修改特征名称为:阀块基体 valuebody.Name = "阀块基体"; } else { System.Windows.Forms.MessageBox.Show("There is no part template available. Please check your options and make sure there is a part template selected, or select a new part template."); } } }
private void b_cut_Click(object sender, EventArgs e) { if (double.TryParse(tb_radius.Text, out radius) == false) { MessageBox.Show("Fehlerhafte Eingabe!"); return; } ModelDoc2 swModel = swApp.ActiveDoc; swModel.Extension.SelectByID2("", "FACE", 0.5 * breite, hoehe, -0.5 * laenge, false, 1, null, 0); swModel.InsertSketch2(true); Sketch swSketch = (Sketch)swModel.GetActiveSketch2(); swModel.CreateCircleByRadius2(0.5 * breite, 0.5 * laenge, 0, radius); swModel.FeatureManager.FeatureCut3(true, false, false, 1, 1, 0.0, 0.0, false, false, false, false, 0, 0, false, false, false, false, false, true, true, false, false, false, 0, 0.0, false); swModel.SaveAsSilent("C:\\temp\\Quader_L_" + tb_laenge.Text + "_B_" + tb_breite.Text + "_H_" + tb_hoehe.Text + "_cut_R_" + tb_radius.Text + ".SLDPRT", true); }
// private void b_create_Click(object sender, EventArgs e) { // Deklarieren der benötigten Variablen double a0x, a0y, lh, rg, PMax, PsiMax; // Auslesen der eingegebenen Werte im Formular if (double.TryParse(label_1.Text, out a0x) == false || double.TryParse(label_2.Text, out a0y) == false || double.TryParse(label_3.Text, out lh) == false || double.TryParse(label_4.Text, out rg) == false || double.TryParse(tb_pmax.Text, out PMax) == false || double.TryParse(label_6.Text, out PsiMax) == false) { MessageBox.Show("Fehlerhafte Eingabe!"); return; } // Erzeugen eines neuen Bauteils ModelDoc2 swModel = (ModelDoc2)swApp.NewPart(); // Herstellen zwischen MatCAD und aktives Arbeitsblatt auslesen Matcad.Application mcApp = (Mathcad.Application)Marshal.GetActiveObject("Mathcad.Applicaiton"); Mathcad.Worksheet mcWks = mcApp.ActiveWorksheet; // neuer Sketch in SolidWorks swModel.Extension.SelectByID2("Ebene vorne", "PLANE", 0, 0, 0, false, 0, null, 0); swModel.InsertSketch2(true); // Setzen der Parameter im MathCAD Arbeitsblatt mcWks.SetValue("a0x", a0x); mcWks.SetValue("a0y", a0y); mcWks.SetValue("lh", lh); mcWks.SetValue("rg", rg); mcWks.SetValue("pmax", PMax); mcWks.SetValue("psimax", PsiMax); double xa = 0.0, ya = 0.0; double xk, yk; Mathcad.NumericValue mcVal; // Schleife zur Berechnung der Stützpunkte for (int i = 0; i < PMax; i++) { // Setzten des Parameters für aktuellen Stützpunkt mcWks.SetValue("pact", i); // Auslesen der berechneten Koordinaten aus MathCAD mcVal = (Mathcad.NumericValue)mcWks.GetValue("X"); xk = mcVal.Real; mcVal = (Mathcad.NumericValue)mcWks.GetValue("Y"); yk = mcVal.Real; if (i > 0) { swModel.CreateLine2(xa / 1000.0, ya / 1000.0, 0, xk / 1000.0, yk / 1000.0, 0); } xa = xk; ya = yk; } // Kreis zeichnen und extrudieren swModel.CreateCircleByRadius2(a0x / 1000.0, a0y / 1000.0, 0.0, 3.0 / 1000.0); swModel.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, 0.01, 0, false, false, false, false, 0, 0, false, false, false, false, false, false, false, 0, 0, false); }
// private void b_createWithSpline_Click(object sender, EventArgs e) { double a0x, a0y, lh, rg, PMax, PsiMax; // Auslesen der eingegebenen Werte im Formular if (double.TryParse(tb_a0x.Text, out a0x) == false || double.TryParse(tb_a0y.Text, out a0y) == false || double.TryParse(tb_lh.Text, out lh) == false || double.TryParse(tb_rg.Text, out rg) == false || double.TryParse(tb_pmax.Text, out PMax) == false || double.TryParse(tb_psimax.Text, out PsiMax) == false) { MessageBox.Show("Fehlerhafte Eingabe!"); return; } // Erzeugen eines neuen Bauteils ModelDoc2 swModel = (ModelDoc2)swApp.NewPart(); // Herstellen zwischen MatCAD und aktives Arbeitsblatt auslesen Matcad.Application mcApp = (Mathcad.Application)Marshal.GetActiveObject("Mathcad.Applicaiton"); Mathcad.Worksheet mcWks = mcApp.ActiveWorksheet; // neuer Sketch in SolidWorks swModel.Extension.SelectByID2("Ebene vorne", "PLANE", 0, 0, 0, false, 0, null, 0); swModel.InsertSketch2(true); // Setzen der Parameter im MathCAD Arbeitsblatt mcWks.SetValue("a0x", a0x); mcWks.SetValue("a0y", a0y); mcWks.SetValue("lh", lh); mcWks.SetValue("rg", rg); mcWks.SetValue("psimax", PsiMax); mcWks.SetValue("pcnt", PMax); double[] PointData = new double[(int)(PMax * 3 + 3)]; int pIndex = 0; double xk, yk; Mathcad.NumericValue mcVal; // Schleife zur Berechnung der Stützpunkte for (int i = 0; i < PMax; i++) { // Setzten des Parameters für aktuellen Stützpunkt mcWks.SetValue("pact", i); // Auslesen der berechneten Koordinaten aus MathCAD mcVal = (Mathcad.NumericValue)mcWks.GetValue("X"); xk = mcVal.Real; mcVal = (Mathcad.NumericValue)mcWks.GetValue("Y"); yk = mcVal.Real; PointData[pIndex] = xk / 1000.0; PointData[pIndex + 1] = yk / 1000.0; PointData[pIndex + 2] = 0; pIndex = pIndex + 3; } swModel.CreateSpline(PointData); swModel.CreateCircleByRadius2(a0x / 1000.0, a0y / 1000.0, 0.0, 3.0 / 1000.0); swModel.FeatureManager.FeatureExtrusion2(true, false, false, 0, 0, 0.01, 0, false, false, false, false, 0, 0, false, false, false, false, false, false, false, 0, 0, false); }
public override void CreatePart() { swApp = SolidWorksSingleton.GetApplication(); DocumentManager.CreateNewPartDoc(); swModel = (ModelDoc2)swApp.ActiveDoc; swFeature = swModel.FeatureByPositionReverse(3); swFeature.Name = "Front"; swModel.Extension.SelectByID2("Front", "PLANE", 0, 0, 0, false, 0, null, 0); swModel.InsertSketch2(true); swModel.CreateLine2(0, 0, 0, XLenght, 0, 0); //swModel.AddDimension2(0,0,0); swModel.CreateLine2(0, 0, 0, 0, YLenght, 0); //swModel.AddDimension2(0, 0, 0); //int markHorizontal = 2; //int markVertical = 4; //swModel.Extension.SelectByID2("Point1@Origin", "EXTSKETCHSEGMENT",0,0,0,false, markHorizontal|markVertical,null,0); object datumDisp = "Point1@Origin"; swModel.SketchManager.FullyDefineSketch(true, true, (int)swSketchFullyDefineRelationType_e.swSketchFullyDefineRelationType_Vertical | (int)swSketchFullyDefineRelationType_e.swSketchFullyDefineRelationType_Horizontal, true, (int)swAutodimScheme_e.swAutodimSchemeBaseline, datumDisp, (int)swAutodimScheme_e.swAutodimSchemeBaseline, datumDisp, (int)swAutodimHorizontalPlacement_e.swAutodimHorizontalPlacementBelow, (int)swAutodimVerticalPlacement_e.swAutodimVerticalPlacementLeft); swModel.InsertSketch2(true); swFeature = swModel.FeatureByPositionReverse(0); swFeature.Name = "Sketch1"; swModel.Extension.SelectByID2("Sketch1", "SKETCH", 0, 0, 0, false, 0, null, 0); swModel.FeatureManager.InsertSheetMetalBaseFlange2(Thickness, false, Thickness, Width, 0, true, 0, 0, 0, null, false, 0, 0, 0, 0, false, false, false, false); BasicOpertations.ChangeEntityName("FACE", MateRef1, Thickness, YLenght / 2, -Width / 2); swModel.Extension.SelectByID2("", "FACE", XLenght / 2, Thickness, -Width / 2, false, 0, null, 0); swModel.InsertSketch2(true); swModel.CreateCircleByRadius2(XLenght - X1, X2, 0, BoltHoles); swModel.CreateCircleByRadius2(XLenght - X1, Width - X2, 0, BoltHoles); swModel.InsertSketch2(true); swFeature = swModel.FeatureByPositionReverse(0); swFeature.Name = "BoltHoles"; swModel.Extension.SelectByID2("BoltHoles", "SKETCH", 0, 0, 0, false, 0, null, 0); BasicOpertations.SimpleCut(); swPart = (PartDoc)swApp.ActiveDoc; swEntity = swPart.GetEntityByName(MateRef1, (int)swSelectType_e.swSelFACES); swEntity.Select4(false, null); swModel.InsertSketch2(true); swModel.CreateCircleByRadius2(Width / 2, YLenght - (PipeHole * 2), 0, PipeHole); swModel.AddDiameterDimension(0, 0, 0); swModel.InsertSketch2(true); BasicOpertations.SimpleCut(); BasicOpertations.ChangeEntityName("FACE", MateRefHole, Thickness / 2, YLenght - PipeHole, -Width / 2); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.Extension.SelectByID2("", "EDGE", XLenght, Thickness / 2, 0, false, 0, null, 0); swModel.Extension.SelectByID2("", "EDGE", XLenght, Thickness / 2, -Width, true, 0, null, 0); BasicOpertations.SimpleFillet(Rad2); swModel.Extension.SelectByID2("", "EDGE", Thickness / 2, YLenght, 0, false, 0, null, 0); swModel.Extension.SelectByID2("", "EDGE", Thickness / 2, YLenght, -Width, true, 0, null, 0); BasicOpertations.SimpleFillet(Rad1); swModel.ClearSelection2(true); swModel.ViewZoomtofit2(); DocumentManager.Save(TargetFolder, FileName, DocumentManager.sw_DocType.part); }
private void button_create_Geom_Click(object sender, RoutedEventArgs e) { #region a test example, not important m = 9; width = 8 / 1000.0; thickness = 1 / 1000.0; l1 = 30 / 1000.0; l2 = 16 / 1000.0; l3 = 21 / 1000.0; F1 = 1; F2 = 37; F3 = 49; l4 = l2; l1_ = l1 - 2 * width; l2_ = l2; l3_ = l3 + 2 * width; l4_ = l4; cell_length = l1 + l3; cell_height = l2 + width; #endregion Count = int.Parse(textBox_count.Text); Random randomSeed = new Random(); Random random_m = new Random(randomSeed.Next()); Random random_width = new Random(randomSeed.Next()); Random random_thickness = new Random(randomSeed.Next()); Random random_l1 = new Random(randomSeed.Next()); Random random_l2 = new Random(randomSeed.Next()); Random random_l3 = new Random(randomSeed.Next()); Random random_F1 = new Random(randomSeed.Next()); Random random_F2 = new Random(randomSeed.Next()); Random random_F3 = new Random(randomSeed.Next()); for (int j = 0; j < Count; j++) { Console.WriteLine(string.Format("---------------------------------now No.{0}", j)); #region generate random Data try { /* change to double * ran_m = random_m.Next(int.Parse(textBox_hm_cells_min.Text), int.Parse(textBox_hm_cellls_max.Text)); * ran_width = random_width.Next(int.Parse(textBox_width_min.Text), int.Parse(textBox_width_max.Text)); * ran_thickness = random_thickness.Next(int.Parse(textBox_thickness_min.Text), int.Parse(textBox_thickness_max.Text)); * ran_l1 = random_l1.Next(int.Parse(textBox_l1_min.Text), int.Parse(textBox_l1_max.Text)); * ran_l2 = random_l2.Next(int.Parse(textBox_l2_min.Text), int.Parse(textBox_l2_max.Text)); * ran_l3 = random_l3.Next(int.Parse(textBox_l3_min.Text), int.Parse(textBox_l3_max.Text)); * ran_F1 = random_F1.Next(int.Parse(textBox_F1_min.Text), int.Parse(textBox_F1_max.Text)); * ran_F2 = random_F2.Next(int.Parse(textBox_F2_min.Text), int.Parse(textBox_F2_max.Text)); * ran_F3 = random_F3.Next(int.Parse(textBox_F3_min.Text), int.Parse(textBox_F3_max.Text)); */ ran_m = random_m.Next(int.Parse(textBox_hm_cells_min.Text), int.Parse(textBox_hm_cellls_max.Text)); ran_width = random_width.NextDouble() * (int.Parse(textBox_width_max.Text) - int.Parse(textBox_width_min.Text)) + double.Parse(textBox_width_min.Text); ran_thickness = random_thickness.NextDouble() * (int.Parse(textBox_thickness_max.Text) - int.Parse(textBox_thickness_min.Text)) + double.Parse(textBox_thickness_min.Text); ran_l1 = random_l1.NextDouble() * (int.Parse(textBox_l1_max.Text) - int.Parse(textBox_l1_min.Text)) + double.Parse(textBox_l1_min.Text); ran_l2 = random_l2.NextDouble() * (int.Parse(textBox_l2_max.Text) - int.Parse(textBox_l2_min.Text)) + double.Parse(textBox_l2_min.Text); ran_l3 = random_l3.NextDouble() * (int.Parse(textBox_l3_max.Text) - int.Parse(textBox_l3_min.Text)) + double.Parse(textBox_l3_min.Text); ran_F1 = random_F1.NextDouble() * (int.Parse(textBox_F1_max.Text) - int.Parse(textBox_F1_min.Text)) + double.Parse(textBox_F1_min.Text); ran_F2 = random_F2.NextDouble() * (int.Parse(textBox_F2_max.Text) - int.Parse(textBox_F2_min.Text)) + double.Parse(textBox_F2_min.Text); ran_F3 = random_F3.NextDouble() * (int.Parse(textBox_F3_max.Text) - int.Parse(textBox_F3_min.Text)) + double.Parse(textBox_F3_min.Text); } catch (Exception) { Console.WriteLine("Input Format Error"); return; } m = ran_m; width = (double)(ran_width / 1000.0); thickness = (double)(ran_thickness / 1000.0); l1 = (double)(ran_l1 / 1000.0); l2 = (double)(ran_l2 / 1000.0); l3 = (double)(ran_l3 / 1000.0); F1 = (double)ran_F1; F2 = (double)ran_F2; F3 = (double)ran_F3; F3 = 0; l4 = l2; l1_ = l1 - 2 * width; l2_ = l2; l3_ = l3 + 2 * width; l4_ = l4; cell_length = l1 + l3; cell_height = l2 + width; #endregion Console.WriteLine(string.Format("{0},{1},{2},{3},{4},{5}", m, width, thickness, l1, l2, l3)); #region geometrie Console.WriteLine("Start creating new Germetrie"); try { swModel = swApp.NewPart(); } catch (Exception) { Console.WriteLine("starting SolidWorks"); try { swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); } catch (Exception) { swApp = new SldWorks(); swApp.Visible = false; } //get MaterialLib strMaterialLib = swApp.GetExecutablePath() + "\\lang\\english\\sldmaterials\\solidworks materials.sldmat"; Console.WriteLine("SolidWorks successfully started"); j--; continue; } swModel.Extension.SelectByID("前视基准面", "PLANE", 0, 0, 0, false, 1, null); swModel.InsertSketch2(true); #region sketch for (int i = 0; i < m; i++) { if (i == 0) { swModel.SketchManager.CreateLine(0, 0, 0, l1 - width, 0, 0); swModel.SketchManager.CreateLine(l1 - width, 0, 0, l1 - width, -l2, 0); swModel.SketchManager.CreateLine(l1 - width, -l2, 0, l1 + l3 - width, -l2, 0); swModel.SketchManager.CreateLine(l1 + l3 - width, -l2, 0, l1 + l3 - width, 0, 0); swModel.SketchManager.CreateLine(0, 0, 0, 0, -width, 0); swModel.SketchManager.CreateLine(0, -width, 0, l1_, -width, 0); swModel.SketchManager.CreateLine(l1_, -width, 0, l1_, -(width + l2_), 0); swModel.SketchManager.CreateLine(l1_, -(width + l2_), 0, l1_ + l3_, -(width + l2_), 0); swModel.SketchManager.CreateLine(l1_ + l3_, -(width + l2_), 0, l1_ + l3_, -width, 0); } else { x_o = i * cell_length - width; y_o = 0; x_o_ = x_o + width; y_o_ = y_o - width; swModel.SketchManager.CreateLine(x_o, y_o, 0, x_o + l1, 0, 0); swModel.SketchManager.CreateLine(x_o + l1, 0, 0, x_o + l1, -l2, 0); swModel.SketchManager.CreateLine(x_o + l1, -l2, 0, x_o + l1 + l3, -l2, 0); swModel.SketchManager.CreateLine(x_o + l1 + l3, -l2, 0, x_o + l1 + l3, 0, 0); swModel.SketchManager.CreateLine(x_o_, y_o_, 0, x_o_ + l1_, y_o_, 0); swModel.SketchManager.CreateLine(x_o_ + l1_, y_o_, 0, x_o_ + l1_, y_o_ - l2_, 0); swModel.SketchManager.CreateLine(x_o_ + l1_, y_o_ - l2_, 0, x_o_ + l1_ + l3_, y_o_ - l2_, 0); swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, y_o_ - l2_, 0, x_o_ + l1_ + l3_, y_o_, 0); } } swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, y_o_, 0, x_o_ + l1_ + l3_, 0, 0); swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, 0, 0, x_o + l1 + l3, 0, 0); #endregion swModel.FeatureManager.FeatureExtrusion2( true, false, false, 0, 0, thickness, 0, false, false, false, false, 0, 0, false, false, false, false, true, true, true, 0, 0, true ); swModel.SaveAsSilent("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_get_TrainingDaten\\Geometrie.sldprt", true); swApp.CloseAllDocuments(true); swApp.OpenDoc("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_get_TrainingDaten\\Geometrie.sldprt", (int)swOpenDocOptions_e.swOpenDocOptions_Silent); Console.WriteLine("Geometrie success"); #endregion #region simulaiton string path_to_cosworks_dll = @"C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\Simulation\cosworks.dll"; errors = swApp.LoadAddIn(path_to_cosworks_dll); COSMOSObject = (CwAddincallback)swApp.GetAddInObject("SldWorks.Simulation"); try { COSMOSWORKS = (CosmosWorks)COSMOSObject.CosmosWorks; } catch (Exception) { Console.WriteLine("something wrong in Simulaiton Add In, start a new one"); continue; } COSMOSWORKS = COSMOSObject.CosmosWorks; //Get active document ActDoc = (CWModelDoc)COSMOSWORKS.ActiveDoc; //Create new static study StudyMngr = (CWStudyManager)ActDoc.StudyManager; Study = (CWStudy)StudyMngr.CreateNewStudy("static study", (int)swsAnalysisStudyType_e.swsAnalysisStudyTypeStatic, 0, out errCode); //Add materials SolidMgr = Study.SolidManager; SolidComp = SolidMgr.GetComponentAt(0, out errCode); SolidBody = SolidComp.GetSolidBodyAt(0, out errCode); intStatus = SolidBody.SetLibraryMaterial(strMaterialLib, "AISI 1020"); //fixed restraints LBCMgr = Study.LoadsAndRestraintsManager; swModel = (ModelDoc2)swApp.ActiveDoc; swModel.ShowNamedView2("", (int)swStandardViews_e.swIsometricView); selectionMgr = (SelectionMgr)swModel.SelectionManager; isSelected = swModel.Extension.SelectByID2("", "FACE", 0, -width / 2.0, thickness / 2.0, false, 0, null, 0); if (isSelected) { object selectedFace = (object)selectionMgr.GetSelectedObject6(1, -1); object[] fixedFaces = { selectedFace }; CWRestraint restraint = (CWRestraint)LBCMgr.AddRestraint((int)swsRestraintType_e.swsRestraintTypeFixed, fixedFaces, null, out errCode); } swModel.ClearSelection2(true); //add force selectionMgr = (SelectionMgr)swModel.SelectionManager; isSelected = swModel.Extension.SelectByID2("", "FACE", x_o + l1 + l3 + (width / 2.0), 0, thickness / 2.0, false, 0, null, 0); if (isSelected) { object selectedFace = (object)selectionMgr.GetSelectedObject6(1, -1); object[] forceAdd = { selectedFace }; selectionMgr = (SelectionMgr)swModel.SelectionManager; swModel.Extension.SelectByID2("", "FACE", x_o + l1 + l3 + width, -(l4 + width) / 2.0, thickness / 2.0, false, 0, null, 0); object selectedFaceToForceDir = (object)selectionMgr.GetSelectedObject6(1, -1); double[] distValue = null; double[] forceValue = null; double[] Force = { F2, F3, F1 }; cwForce = (CWForce)LBCMgr.AddForce3((int)swsForceType_e.swsForceTypeForceOrMoment, (int)swsSelectionType_e.swsSelectionFaceEdgeVertexPoint, 2, 0, 0, 0, (distValue), (forceValue), false, true, (int)swsBeamNonUniformLoadDef_e.swsTotalLoad, 0, 7, 0.0, Force, false, false, (forceAdd), (selectedFaceToForceDir), false, out errCode); //i have tried to figure out these arguments for one day, keep them and dont't change them. //the way to check cwForce : cwForce.GetForceComponentValues() //ForceComponet: [int b1, // 1 if x-direction hat Force-komponent, else 0 // int b2, // 1 if y-direction hat Force-komponent, else 0 // int b3, // 1 if z-direction hat Force-komponent, else 0 // double d1, // Force-komponent in x // double d2, // Force-komponent in y // double d3 // Force-komponent in z // ] //PS: the definition of xyz seems like not the same as the global XYZ system in SW. swModel.ClearSelection2(true); //meshing CWMesh CWMeshObj = default(CWMesh); CWMeshObj = Study.Mesh; CWMeshObj.MesherType = (int)swsMesherType_e.swsMesherTypeStandard; CWMeshObj.Quality = (int)swsMeshQuality_e.swsMeshQualityDraft; errCode = Study.CreateMesh(0, MeshEleSize, MeshTol); CWMeshObj = null; //run analysis errCode = Study.RunAnalysis(); if (errCode != 0) { Console.WriteLine(string.Format("RunAnalysis errCode = {0}", errCode)); Console.WriteLine(string.Format("RunAnalysis failed")); swApp.CloseAllDocuments(true); errors = swApp.UnloadAddIn(path_to_cosworks_dll); Console.WriteLine(string.Format("ready to start a new one")); continue; } Console.WriteLine("RunAnalysis successed, ready to get results"); //get results CWFeatobj = Study.Results; //get max von Mieses stress Stress = (object[])CWFeatobj.GetMinMaxStress((int)swsStressComponent_e.swsStressComponentVON, 0, 0, null, (int)swsStrengthUnit_e.swsStrengthUnitNewtonPerSquareMillimeter, out errCode); maxStress = (float)Stress[3]; //Stress: {node_with_minimum_stress, minimum_stress, node_with_maximum_stress, maximum_stress} Console.WriteLine(maxStress); /* * if (maxStress >= 351.6) * { * Console.WriteLine("out of yield stress, start a new example"); * errors = swApp.UnloadAddIn(path_to_cosworks_dll); * swApp.CloseAllDocuments(true); * j--; * continue; * } */ //get max URES displacement Disp = (object[])CWFeatobj.GetMinMaxDisplacement((int)swsDisplacementComponent_e.swsDisplacementComponentURES, 0, null, (int)swsLinearUnit_e.swsLinearUnitMillimeters, out errCode); maxDisp = (float)Disp[3]; //Disp: {node_with_minimum_displacement, minimum_displacement, node_with_maximum_displacement, maximum_displacement} CWFeatobj = null; Console.WriteLine(string.Format("max Displacement: {0:f4} mm", maxDisp)); //output to Excel exlSheet.Cells[j + 2, 1] = m; exlSheet.Cells[j + 2, 2] = width * 1000; exlSheet.Cells[j + 2, 3] = thickness * 1000; exlSheet.Cells[j + 2, 4] = l1 * 1000; exlSheet.Cells[j + 2, 5] = l2 * 1000; exlSheet.Cells[j + 2, 6] = l3 * 1000; exlSheet.Cells[j + 2, 7] = F1; exlSheet.Cells[j + 2, 8] = F2; exlSheet.Cells[j + 2, 9] = F3; exlSheet.Cells[j + 2, 10] = maxStress; exlSheet.Cells[j + 2, 11] = maxDisp; if (j % 5 == 0) { exlBook.Save();//C:\Users\Zhao\Documents\工作簿1.xlsx } errors = swApp.UnloadAddIn(path_to_cosworks_dll); swApp.CloseAllDocuments(true); } #endregion } exlBook.SaveCopyAs("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_get_TrainingDaten\\W_Form_simulationDaten_" + GetTimeStamp() + "_F3=0" + ".xlsx"); exlBook.Save();//C:\Users\zhaojie\Documents\工作簿1.xlsx exlApp.Quit(); }
public void CreateHeaterCenter(string heaterPathName) { ISketchPoint startPoint = null; ISketchPoint endPoint = null; List <SegmentData> list = new List <SegmentData>(); List <SegmentData> list2 = new List <SegmentData>(); List <SegmentData> list3 = new List <SegmentData>(); List <SegmentData> list4 = new List <SegmentData>(); _swApp.ActivateDoc(_swPartModel.GetTitle()); _swPartModel.ShowNamedView2("*Front", 1); ISketchArc arc; double length; list2.Clear(); list.Clear(); _swPartModel.Extension.SelectByID2(heaterPathName, "SKETCH", 0.0, 0.0, 0.0, true, 0, null, 0); _swPartModel.ViewZoomToSelection(); ISelectionMgr iSelectionManager = _swPartModel.ISelectionManager; IFeature feature = iSelectionManager.GetSelectedObject6(1, 0); ISketch sketch = feature.GetSpecificFeature2(); Array array = sketch.GetSketchSegments(); Array array2 = sketch.GetSketchPoints2(); foreach (ISketchSegment segment in array) { ISketchSegment segment2 = segment; segment2.Select(true); if (!segment2.ConstructionGeometry) { if (segment2.GetType() == 0) { ISketchLine line = (ISketchLine)segment2; startPoint = line.IGetStartPoint2(); endPoint = line.IGetEndPoint2(); } if (segment2.GetType() == 1) { arc = (ISketchArc)segment2; startPoint = arc.IGetStartPoint2(); endPoint = arc.IGetEndPoint2(); } SegmentData item = new SegmentData(segment2, startPoint, endPoint); list.Add(item); } _swPartModel.ClearSelection2(true); } for (int i = 0; i < list.Count; i++) { int num9 = 0; list2.Add(list[0]); list.Remove(list[0]); for (int m = 0; m < list.Count; m++) { list2[0].Segment.Select(false); list[m].Segment.Select(false); if ((Math.Round(list2[0].StartPoint.X, 5) == Math.Round(list[m].StartPoint.X, 5)) && (Math.Round(list2[0].StartPoint.Y, 5) == Math.Round(list[m].StartPoint.Y, 5))) { num9++; } if ((Math.Round(list2[0].EndPoint.X, 5) == Math.Round(list[m].EndPoint.X, 5)) && (Math.Round(list2[0].EndPoint.Y, 5) == Math.Round(list[m].EndPoint.Y, 5))) { num9++; } if ((Math.Round(list2[0].EndPoint.X, 5) == Math.Round(list[m].StartPoint.X, 5)) && (Math.Round(list2[0].EndPoint.Y, 5) == Math.Round(list[m].StartPoint.Y, 5))) { num9++; } if ((Math.Round(list2[0].StartPoint.X, 5) == Math.Round(list[m].EndPoint.X, 5)) && (Math.Round(list2[0].StartPoint.Y, 5) == Math.Round(list[m].EndPoint.Y, 5))) { num9++; } _swPartModel.ClearSelection2(true); if (num9 == 2) { list.Add(list2[0]); list2.Remove(list2[0]); break; } } if (num9 == 1) { list2[0].Segment.Select(true); break; } } int num = 0; for (int j = 0; j < list.Count; j++) { list2[num].Segment.Select(true); list[j].Segment.Select(false); if ((Math.Round(list2[num].StartPoint.X, 5) == Math.Round(list[j].StartPoint.X, 5)) && (Math.Round(list2[num].StartPoint.Y, 5) == Math.Round(list[j].StartPoint.Y, 5))) { list2.Add(list[j]); list.Remove(list[j]); num++; j = -1; } else if ((Math.Round(list2[num].EndPoint.X, 5) == Math.Round(list[j].EndPoint.X, 5)) && (Math.Round(list2[num].EndPoint.Y, 5) == Math.Round(list[j].EndPoint.Y, 5))) { list2.Add(list[j]); list.Remove(list[j]); num++; j = -1; } else if ((Math.Round(list2[num].EndPoint.X, 5) == Math.Round(list[j].StartPoint.X, 5)) && (Math.Round(list2[num].EndPoint.Y, 5) == Math.Round(list[j].StartPoint.Y, 5))) { list2.Add(list[j]); list.Remove(list[j]); num++; j = -1; } else if ((Math.Round(list2[num].StartPoint.X, 5) == Math.Round(list[j].EndPoint.X, 5)) && (Math.Round(list2[num].StartPoint.Y, 5) == Math.Round(list[j].EndPoint.Y, 5))) { list2.Add(list[j]); list.Remove(list[j]); num++; j = -1; } } _swPartModel.ClearSelection(); _swPartModel.Extension.SelectByID2(heaterPathName, "SKETCH", 0.0, 0.0, 0.0, false, 0, null, 0); _swPartModel.EditSketch(); foreach (ISketchPoint point3 in array2) { point3.Select(false); if (point3.Type == 1) { _swPartModel.EditDelete(); } } double num2 = 0.0; foreach (SegmentData data2 in list2) { data2.Segment.Select(false); length = data2.Segment.GetLength(); num2 += length; } _swPartModel.ClearSelection(); double num4 = num2 / 2.0; length = 0.0; int num5 = 0; double num6 = 0.0; for (int k = 0; k < list2.Count; k++) { list2[k].Segment.Select(false); length += list2[k].Segment.GetLength(); if (num4 < length) { num5 = k; double num7 = Math.Abs((double)(length - num4)); num6 = (list2[num5].Segment.GetLength() - num7) / list2[num5].Segment.GetLength(); break; } } _swPartModel.ClearSelection(); if (list2[num5].Segment.GetType() == 0) { double num13 = 0.0; double x = list2[num5].StartPoint.X; double y = list2[num5].StartPoint.Y; double num16 = list2[num5].EndPoint.X; double num17 = list2[num5].EndPoint.Y; if ((Math.Round(num16, 6) == Math.Round(list2[num5 - 1].StartPoint.X, 6)) && (Math.Round(num17, 6) == Math.Round(list2[num5 - 1].StartPoint.Y, 6))) { num16 = list2[num5].StartPoint.X; num17 = list2[num5].StartPoint.Y; x = list2[num5].EndPoint.X; y = list2[num5].EndPoint.Y; } else if ((Math.Round(num16, 6) == Math.Round(list2[num5 - 1].EndPoint.X, 6)) && (Math.Round(num17, 6) == Math.Round(list2[num5 - 1].EndPoint.Y, 6))) { num16 = list2[num5].StartPoint.X; num17 = list2[num5].StartPoint.Y; x = list2[num5].EndPoint.X; y = list2[num5].EndPoint.Y; } double pointX = x + ((num16 - x) * num6); double pointY = y + ((num17 - y) * num6); _swPartModel.SetAddToDB(true); if (_swPartModel.CreatePoint2(pointX, pointY, 0.0) != null) { _swPartModel.SketchAddConstraints("sgFixed"); } if (x == num16) { num13 = 1.5707963267948966; } if (y == num17) { num13 = 3.1415926535897931; } if ((x != num16) && !(y == num17)) { num13 = Math.Atan((num17 - y) / (num16 - x)); } if (num13 > 3.1415926535897931) { num13 -= 3.1415926535897931; } ISketchSegment segment3 = _swPartModel.ICreateLine2(pointX + (0.005 * Math.Cos(num13 + 1.5707963267948966)), pointY + (0.005 * Math.Sin(num13 + 1.5707963267948966)), 0.0, pointX + (0.005 * Math.Cos(num13 + 4.71238898038469)), pointY + (0.005 * Math.Sin(num13 + 4.71238898038469)), 0.0); _swPartModel.SketchAddConstraints("sgFIXED"); segment3.ConstructionGeometry = true; _swPartModel.SetAddToDB(false); _swPartModel.ClearSelection2(true); _swPartModel.InsertSketch2(true); } if (list2[num5].Segment.GetType() == 1) { arc = (ISketchArc)list2[num5].Segment; startPoint = arc.IGetStartPoint2(); endPoint = arc.IGetEndPoint2(); ISketchPoint point4 = arc.IGetCenterPoint2(); int rotationDir = arc.GetRotationDir(); double num21 = 0.0; double num22 = 0.0; double num23 = list2[num5].Segment.GetLength(); double radius = arc.GetRadius(); double num25 = (num6 * num23) / radius; double num26 = startPoint.X; double num27 = startPoint.Y; double num28 = endPoint.X; double num29 = endPoint.Y; double num30 = point4.X; double num31 = point4.Y; if ((Math.Round(num28, 6) == Math.Round(list2[num5 - 1].StartPoint.X, 6)) && (Math.Round(num29, 6) == Math.Round(list2[num5 - 1].StartPoint.Y, 6))) { num26 = endPoint.X; num27 = endPoint.Y; rotationDir = -1 * rotationDir; } else if ((Math.Round(num28, 6) == Math.Round(list2[num5 - 1].EndPoint.X, 6)) && (Math.Round(num29, 6) == Math.Round(list2[num5 - 1].EndPoint.Y, 6))) { num26 = endPoint.X; num27 = endPoint.Y; rotationDir = -1 * rotationDir; } if ((num30 != num26) && !(num31 == num27)) { num21 = Math.Atan((num31 - num27) / (num30 - num26)); } if (Math.Round(num30, 8) == Math.Round(num26, 8)) { if (Math.Round(num31, 8) > Math.Round(num27, 8)) { num21 = 4.71238898038469; } else if (Math.Round(num31, 8) < Math.Round(num27, 8)) { num21 = 1.5707963267948966; } } else if (Math.Round(num31, 8) == Math.Round(num27, 8)) { if (Math.Round(num30, 8) > Math.Round(num26, 8)) { num21 = 3.1415926535897931; } else if (Math.Round(num30, 8) < Math.Round(num26, 8)) { if (rotationDir > 0) { num21 = 0.0; } else { num21 = 6.2831853071795862; } } } if ((Math.Round(num30, 8) < Math.Round(num26, 8)) && (Math.Round(num31, 8) < Math.Round(num27, 8))) { num22 = num21 + (rotationDir * num25); } else if ((Math.Round(num30, 8) < Math.Round(num26, 8)) && (Math.Round(num31, 8) > Math.Round(num27, 8))) { num22 = (6.2831853071795862 + num21) + (rotationDir * num25); } else if ((Math.Round(num30, 8) > Math.Round(num26, 8)) && (Math.Round(num31, 8) > Math.Round(num27, 8))) { num22 = (3.1415926535897931 + num21) + (rotationDir * num25); } else if ((Math.Round(num30, 8) > Math.Round(num26, 8)) && (Math.Round(num31, 8) < Math.Round(num27, 8))) { num22 = (3.1415926535897931 + num21) + (rotationDir * num25); } else if (Math.Round(num30, 8) == Math.Round(num26, 8)) { num22 = num21 + (rotationDir * num25); } else if (Math.Round(num31, 8) == Math.Round(num27, 8)) { num22 = num21 + (rotationDir * num25); } num22 = Math.Round(num22, 6); double num32 = num30 + (radius * Math.Cos(num22)); double num33 = num31 + (radius * Math.Sin(num22)); bool flag29 = true; if (_swPartModel.Extension.SelectByID2("", "SKETCHPOINT", num32, num33, 0.0, false, 0, null, 0)) { ISketchPoint point5 = iSelectionManager.GetSelectedObject6(0, 1); if ((point5 != null) && ((Math.Round(point5.X, 6) == Math.Round(num32, 6)) && (Math.Round(point5.Y, 6) == Math.Round(num33, 6)))) { flag29 = false; } } _swPartModel.SetAddToDB(true); if (flag29 && (_swPartModel.CreatePoint2(num32, num33, 0.0) != null)) { _swPartModel.SketchAddConstraints("sgFIXED"); _swPartModel.ICreateLine2(num30, num31, 0.0, num32, num33, 0.0).ConstructionGeometry = true; } _swPartModel.SetAddToDB(false); _swPartModel.ClearSelection2(true); _swPartModel.InsertSketch2(true); } }
private void Button_generateFEM_Click(object sender, RoutedEventArgs e) { #region Variable definition int m; //how many cells int Count; // how many data double width, thickness, l1, l2, l3, F1, F2, F3; double l4, l1_, l2_, l3_, l4_, cell_length, cell_height; double x_o = 0.0; double y_o = 0.0; double x_o_ = 0.0; double y_o_ = 0.0; const double MeshEleSize = 2.0; const double MeshTol = 0.1; string strMaterialLib = null; object[] Disp = null; object[] Stress = null; ModelDoc2 swModel = null; SelectionMgr selectionMgr = null; CosmosWorks COSMOSWORKS = null; CwAddincallback COSMOSObject = default(CwAddincallback); CWModelDoc ActDoc = default(CWModelDoc); CWStudyManager StudyMngr = default(CWStudyManager); CWStudy Study = default(CWStudy); CWSolidManager SolidMgr = default(CWSolidManager); CWSolidBody SolidBody = default(CWSolidBody); CWSolidComponent SolidComp = default(CWSolidComponent); CWForce cwForce = default(CWForce); CWLoadsAndRestraintsManager LBCMgr = default(CWLoadsAndRestraintsManager); CWResults CWFeatobj = default(CWResults); bool isSelected; float maxDisp = 0.0f; float maxStress = 0.0f; int intStatus = 0; int errors = 0; int errCode = 0; int warnings = 0; int ran_m, ran_width, ran_thickness, ran_l1, ran_l2, ran_l3, ran_F1, ran_F2, ran_F3; Excel.Application exlApp; Excel.Workbook exlBook; Excel.Worksheet exlSheet; #endregion #region read data from UI try { m = int.Parse(textBox_hm_cells.Text); width = double.Parse(textBox_width.Text) / 1000.0; thickness = double.Parse(textBox_thickness.Text) / 1000.0; l1 = double.Parse(textBox_l1.Text) / 1000.0; l2 = double.Parse(textBox_l2.Text) / 1000.0; l3 = double.Parse(textBox_l3.Text) / 1000.0; F1 = double.Parse(textBox_F1.Text); F2 = double.Parse(textBox_F2.Text); F3 = double.Parse(textBox_F3.Text); } catch (Exception) { MessageBox.Show("input format error, check input data"); return; } l4 = l2; l1_ = l1 - 2 * width; l2_ = l2; l3_ = l3 + 2 * width; l4_ = l4; cell_length = l1 + l3; cell_height = l2 + width; #endregion #region geometrie Console.WriteLine("Start creating new Germetrie"); swModel = swApp.NewPart(); swModel.Extension.SelectByID("前视基准面", "PLANE", 0, 0, 0, false, 1, null); swModel.InsertSketch2(true); #region sketch for (int i = 0; i < m; i++) { if (i == 0) { swModel.SketchManager.CreateLine(0, 0, 0, l1 - width, 0, 0); swModel.SketchManager.CreateLine(l1 - width, 0, 0, l1 - width, -l2, 0); swModel.SketchManager.CreateLine(l1 - width, -l2, 0, l1 + l3 - width, -l2, 0); swModel.SketchManager.CreateLine(l1 + l3 - width, -l2, 0, l1 + l3 - width, 0, 0); swModel.SketchManager.CreateLine(0, 0, 0, 0, -width, 0); swModel.SketchManager.CreateLine(0, -width, 0, l1_, -width, 0); swModel.SketchManager.CreateLine(l1_, -width, 0, l1_, -(width + l2_), 0); swModel.SketchManager.CreateLine(l1_, -(width + l2_), 0, l1_ + l3_, -(width + l2_), 0); swModel.SketchManager.CreateLine(l1_ + l3_, -(width + l2_), 0, l1_ + l3_, -width, 0); } else { x_o = i * cell_length - width; y_o = 0; x_o_ = x_o + width; y_o_ = y_o - width; swModel.SketchManager.CreateLine(x_o, y_o, 0, x_o + l1, 0, 0); swModel.SketchManager.CreateLine(x_o + l1, 0, 0, x_o + l1, -l2, 0); swModel.SketchManager.CreateLine(x_o + l1, -l2, 0, x_o + l1 + l3, -l2, 0); swModel.SketchManager.CreateLine(x_o + l1 + l3, -l2, 0, x_o + l1 + l3, 0, 0); swModel.SketchManager.CreateLine(x_o_, y_o_, 0, x_o_ + l1_, y_o_, 0); swModel.SketchManager.CreateLine(x_o_ + l1_, y_o_, 0, x_o_ + l1_, y_o_ - l2_, 0); swModel.SketchManager.CreateLine(x_o_ + l1_, y_o_ - l2_, 0, x_o_ + l1_ + l3_, y_o_ - l2_, 0); swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, y_o_ - l2_, 0, x_o_ + l1_ + l3_, y_o_, 0); } } swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, y_o_, 0, x_o_ + l1_ + l3_, 0, 0); swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, 0, 0, x_o + l1 + l3, 0, 0); #endregion swModel.FeatureManager.FeatureExtrusion2( true, false, false, 0, 0, thickness, 0, false, false, false, false, 0, 0, false, false, false, false, true, true, true, 0, 0, true ); swModel.SaveAsSilent("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_FEM_NN_GUI\\Geometrie.sldprt", true); swApp.CloseAllDocuments(true); swApp.OpenDoc("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_FEM_NN_GUI\\Geometrie.sldprt", (int)swOpenDocOptions_e.swOpenDocOptions_Silent); Console.WriteLine("Geometrie success"); #endregion #region simulaiton string path_to_cosworks_dll = @"C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\Simulation\cosworks.dll"; errors = swApp.LoadAddIn(path_to_cosworks_dll); COSMOSObject = (CwAddincallback)swApp.GetAddInObject("SldWorks.Simulation"); try { COSMOSWORKS = (CosmosWorks)COSMOSObject.CosmosWorks; } catch (Exception) { Console.WriteLine("something wrong in Simulaiton Add In, start a new one"); swApp.CloseAllDocuments(true); return; } COSMOSWORKS = COSMOSObject.CosmosWorks; //Get active document ActDoc = (CWModelDoc)COSMOSWORKS.ActiveDoc; //Create new static study StudyMngr = (CWStudyManager)ActDoc.StudyManager; Study = (CWStudy)StudyMngr.CreateNewStudy("static study", (int)swsAnalysisStudyType_e.swsAnalysisStudyTypeStatic, 0, out errCode); //Add materials //get MaterialLib strMaterialLib = swApp.GetExecutablePath() + "\\lang\\english\\sldmaterials\\solidworks materials.sldmat"; SolidMgr = Study.SolidManager; SolidComp = SolidMgr.GetComponentAt(0, out errCode); SolidBody = SolidComp.GetSolidBodyAt(0, out errCode); intStatus = SolidBody.SetLibraryMaterial(strMaterialLib, "AISI 1020"); //fixed restraints LBCMgr = Study.LoadsAndRestraintsManager; swModel = (ModelDoc2)swApp.ActiveDoc; swModel.ShowNamedView2("", (int)swStandardViews_e.swIsometricView); selectionMgr = (SelectionMgr)swModel.SelectionManager; isSelected = swModel.Extension.SelectByID2("", "FACE", 0, -width / 2.0, thickness / 2.0, false, 0, null, 0); if (isSelected) { object selectedFace = (object)selectionMgr.GetSelectedObject6(1, -1); object[] fixedFaces = { selectedFace }; CWRestraint restraint = (CWRestraint)LBCMgr.AddRestraint((int)swsRestraintType_e.swsRestraintTypeFixed, fixedFaces, null, out errCode); } swModel.ClearSelection2(true); //add force selectionMgr = (SelectionMgr)swModel.SelectionManager; isSelected = swModel.Extension.SelectByID2("", "FACE", x_o + l1 + l3 + (width / 2.0), 0, thickness / 2.0, false, 0, null, 0); if (isSelected) { object selectedFace = (object)selectionMgr.GetSelectedObject6(1, -1); object[] forceAdd = { selectedFace }; selectionMgr = (SelectionMgr)swModel.SelectionManager; swModel.Extension.SelectByID2("", "FACE", x_o + l1 + l3 + width, -(l4 + width) / 2.0, thickness / 2.0, false, 0, null, 0); object selectedFaceToForceDir = (object)selectionMgr.GetSelectedObject6(1, -1); double[] distValue = null; double[] forceValue = null; double[] Force = { F2, F3, F1 }; cwForce = (CWForce)LBCMgr.AddForce3((int)swsForceType_e.swsForceTypeForceOrMoment, (int)swsSelectionType_e.swsSelectionFaceEdgeVertexPoint, 2, 0, 0, 0, (distValue), (forceValue), false, true, (int)swsBeamNonUniformLoadDef_e.swsTotalLoad, 0, 7, 0.0, Force, false, false, (forceAdd), (selectedFaceToForceDir), false, out errCode); //i have tried to figure out these arguments for one day, keep them and dont't change them. //the way to check cwForce : cwForce.GetForceComponentValues() //ForceComponet: [int b1, // 1 if x-direction hat Force-komponent, else 0 // int b2, // 1 if y-direction hat Force-komponent, else 0 // int b3, // 1 if z-direction hat Force-komponent, else 0 // double d1, // Force-komponent in x // double d2, // Force-komponent in y // double d3 // Force-komponent in z // ] //PS: the definition of xyz seems like not the same as the global XYZ system in SW. swModel.ClearSelection2(true); //meshing CWMesh CWMeshObj = default(CWMesh); CWMeshObj = Study.Mesh; CWMeshObj.MesherType = (int)swsMesherType_e.swsMesherTypeStandard; CWMeshObj.Quality = (int)swsMeshQuality_e.swsMeshQualityDraft; errCode = Study.CreateMesh(0, MeshEleSize, MeshTol); CWMeshObj = null; //run analysis errCode = Study.RunAnalysis(); if (errCode != 0) { Console.WriteLine(string.Format("RunAnalysis errCode = {0}", errCode)); Console.WriteLine(string.Format("RunAnalysis failed")); errors = swApp.UnloadAddIn(path_to_cosworks_dll); swApp.CloseAllDocuments(true); Console.WriteLine(string.Format("please start a new one")); return; } Console.WriteLine("RunAnalysis successed, ready to get results"); //get results CWFeatobj = Study.Results; //get max von Mieses stress Stress = (object[])CWFeatobj.GetMinMaxStress((int)swsStressComponent_e.swsStressComponentVON, 0, 0, null, (int)swsStrengthUnit_e.swsStrengthUnitNewtonPerSquareMillimeter, out errCode); maxStress = (float)Stress[3]; //Stress: {node_with_minimum_stress, minimum_stress, node_with_maximum_stress, maximum_stress} Console.WriteLine(maxStress); if (maxStress >= 351.6) { Console.WriteLine("out of yield stress, start a new example"); errors = swApp.UnloadAddIn(path_to_cosworks_dll); swApp.CloseAllDocuments(true); textBox_FEM_result.Text = "out of yield stress"; return; } //get max URES displacement Disp = (object[])CWFeatobj.GetMinMaxDisplacement((int)swsDisplacementComponent_e.swsDisplacementComponentURES, 0, null, (int)swsLinearUnit_e.swsLinearUnitMillimeters, out errCode); maxDisp = (float)Disp[3]; //Disp: {node_with_minimum_displacement, minimum_displacement, node_with_maximum_displacement, maximum_displacement} CWFeatobj = null; Console.WriteLine(string.Format("max Displacement: {0:f4} mm", maxDisp)); textBox_FEM_result.Text = maxDisp.ToString(); } else { Console.WriteLine("not selected"); } #endregion errors = swApp.UnloadAddIn(path_to_cosworks_dll); swApp.CloseAllDocuments(true); }