/// <summary> /// 关闭所有打开的SW文档 /// </summary> private void closeAllSWDoc() { if (m_SwApp != null) { m_SwApp.CloseAllDocuments(true); } }
private void CopySolidworksFile(string file_from, string file_to, string replease_from, string replact_to) { SldWorks swApp = Utility.ConnectToSolidWorks(); string source = System.IO.Path.GetDirectoryName(file_from); string target = System.IO.Path.GetDirectoryName(file_to); string sourcefile = file_from;; string tempfile = System.IO.Path.GetFileName(file_to); bool traverse = false; bool search = false; bool addreadonlyinfo = false; object[] depends = null; string[] sourcefiles = null; string[] targetfiles = null; int idx = 0; int sourcecount = 0; int copyopt = 0; int errors = 0; int lind = 0; ModelDoc2 doc = default(ModelDoc2); // sourcefile = file_from; tempfile = file_to;// System.IO.Path.GetDirectoryName(file_to); lind = tempfile.LastIndexOf("\\"); target = tempfile.Substring(0, lind); traverse = true; search = true; addreadonlyinfo = false; depends = (object[])swApp.GetDocumentDependencies2(sourcefile, traverse, search, addreadonlyinfo); if ((depends == null)) { return; } idx = 1; while (idx <= depends.GetUpperBound(0)) { Array.Resize(ref sourcefiles, sourcecount + 1); Array.Resize(ref targetfiles, sourcecount + 1); sourcefiles[sourcecount] = (string)depends[idx]; lind = sourcefiles[sourcecount].LastIndexOf("\\"); targetfiles[sourcecount] = target + sourcefiles[sourcecount].Substring(lind, sourcefiles[sourcecount].Length - lind); sourcecount = sourcecount + 1; idx = idx + 2; } swApp.CloseAllDocuments(true); copyopt = (int)swMoveCopyOptions_e.swMoveCopyOptionsOverwriteExistingDocs; errors = swApp.CopyDocument(sourcefile, target + @"\" + System.IO.Path.GetFileName(sourcefile), (sourcefiles), (targetfiles), (int)copyopt); }
public static void CloseAllDocuments() { if (swApp != null) { swApp.CloseAllDocuments(true); } }
void IDisposable.Dispose() { try { _app.CloseAllDocuments(true); _app.ExitApp(); _app = null; } // ReSharper disable EmptyGeneralCatchClause catch { } // ReSharper restore EmptyGeneralCatchClause }
public static void CloseDoc(SldWorks iswApp) { int err = -1; int warn = -1; iswApp.OpenDoc6(AppDomain.CurrentDomain.BaseDirectory + @"RectanglePlug\PlugTopBox.SLDPRT", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_AutoMissingConfig, "圆壳", ref err, ref warn); iswApp.OpenDoc6(AppDomain.CurrentDomain.BaseDirectory + @"RectanglePlug\PlugBottomBox.SLDPRT", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_AutoMissingConfig, "", ref err, ref warn); iswApp.OpenDoc6(AppDomain.CurrentDomain.BaseDirectory + @"RectanglePlug\PlugWire.SLDPRT", (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_AutoMissingConfig, "", ref err, ref warn); MessageBox.Show("三个文档已打开,点击后,将关闭PlugTopBox.SLDPRT"); iswApp.CloseDoc(AppDomain.CurrentDomain.BaseDirectory + @"RectanglePlug\PlugTopBox.SLDPRT"); MessageBox.Show("关闭成功,再次点击将关闭所有文档"); iswApp.CloseAllDocuments(true); MessageBox.Show("所有文档已关闭"); }
internal static void Dispose() { if (swApp != null && !SwWasStarted) { swApp.CloseAllDocuments(true); swApp.ExitApp(); swApp = null; //if process is not close try { foreach (Process proc in Process.GetProcessesByName("SldWorks")) { proc.Kill(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
static void Main() { ModelDoc2 swModelDoc = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); PackAndGo swPackAndGo = default(PackAndGo); //SldWorks swApp = new SldWorks(); //GetSolidworks getSW = new GetSolidworks(); Tuple <SldWorks, Process> processes = GetSolidworks.Solidworks(1); swApp = processes.Item1; Process = processes.Item2; //swApp.Visible = false; //add another line to get item 2 which is the process which you can then use to kill when it derps /* To be used to more easily choose which assemblies to pack and go * List<string> trNames = new List<string>(new string[] { "500", "525"}); * List<string> cmtNames = new List<string>(new string[] { "500", "525" }); * * for (int i = 0; i <= trNames.Count - 1; i++) * { * trNames[i] = "TR-34-20-" + trNames[i]; * } * for (int i = 0; i <= cmtNames.Count - 1; i++) * { * cmtNames[i] = "CMT-34-20-" + cmtNames[i]; * } */ List <string> modelNames = new List <string>(new string[] { "TR-34-20-400", "TR-34-20-425", "TR-34-20-500", "TR-34-20-525", "TR-34-20-530", "TR-34-20-600", "TR-34-20-625", "TR-34-20-630", "TR-34-20-700", "TR-34-20-725", "TR-34-20-730", "TR-34-20-900", "TR-34-20-925", "TR-34-20-930", "CMT-34-20-400", "CMT-34-20-425", "CMT-34-20-500", "CMT-34-20-525", "CMT-34-20-530", "CMT-34-20-600", "CMT-34-20-625", "CMT-34-20-630", "CMT-34-20-700", "CMT-34-20-725", "CMT-34-20-730", "CMT-34-20-900", "CMT-34-20-925", "CMT-34-20-930" }); //List<string> modelNames = new List<string>(new string[] { "TR-34-20-400", "TR-34-20-425", "TR-34-20-500" }); int modelCount = modelNames.Count; while (modelNames.Count > 0) { SetCheckTimer(); int j = 0; try { string openFile = null; bool status = false; int warnings = 0; int errors = 0; int i = 0; int namesCount = 0; string savePath = null; int[] statuses = null; openFile = @"C:\Configurator\" + modelNames[j] + ".sldasm"; Debug.Print("Performing pack and go on " + modelNames[j]); Console.WriteLine("Performing pack and go on " + modelNames[j]); swModelDoc = swApp.OpenDoc6(openFile, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); swModelDoc.Visible = false; swApp.Visible = false; //opendoc6 seems to remove the visiblility setting swModelDocExt = (ModelDocExtension)swModelDoc.Extension; swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo(); savePath = @"C:\Configurator\PackandGoTest\test.zip"; status = swPackAndGo.SetSaveToName(false, savePath); swPackAndGo.FlattenToSingleFolder = true; namesCount = swPackAndGo.GetDocumentNamesCount(); Debug.Print(" Number of model documents: " + namesCount); Console.WriteLine(" Number of model documents: " + namesCount); // Include any drawings, SOLIDWORKS Simulation results, and SOLIDWORKS Toolbox components swPackAndGo.IncludeDrawings = true; //Debug.Print(" Include drawings: " + swPackAndGo.IncludeDrawings); swPackAndGo.IncludeSimulationResults = false; //Debug.Print(" Include SOLIDWORKS Simulation results: " + swPackAndGo.IncludeSimulationResults); swPackAndGo.IncludeToolboxComponents = false; //Debug.Print(" Include SOLIDWORKS Toolbox components: " + swPackAndGo.IncludeToolboxComponents); swPackAndGo.IncludeSuppressed = true; // Verify document paths and filenames after adding prefix and suffix object getFileNames; object getDocumentStatus; status = swPackAndGo.GetDocumentSaveToNames(out getFileNames, out getDocumentStatus); string[] pgGetFileNames = (string[])getFileNames; if (pgGetFileNames.Length == 0) { status = swPackAndGo.GetDocumentSaveToNames(out getFileNames, out getDocumentStatus); pgGetFileNames = (string[])getFileNames; } for (int z = 0; z < pgGetFileNames.Length; z++) { if (pgGetFileNames[z].StartsWith(@"c:\configurator")) { } else { Debug.Print(pgGetFileNames[z]); Console.WriteLine("Please Remove This File and Try Again: " + pgGetFileNames[z]); } pgGetFileNames[z] = GetProperFilePathCapitalization(pgGetFileNames[z]); } swPackAndGo.SetDocumentSaveToNames(pgGetFileNames); //for (int z = 0;z< ) //pgGetFileNames = (string[])getFileNames; /*This section is unnecessary and clutters the debug window, add back in at own preference * Debug.Print(""); * Debug.Print(" My Pack and Go path and filenames after adding prefix and suffix: "); * for (i = 0; i <= namesCount - 1; i++) * { * Debug.Print(" My path and filename is: " + pgGetFileNames[i]); * } */ // Pack and Go statuses = (int[])swModelDocExt.SavePackAndGo(swPackAndGo); //swApp.CloseDoc(modelNames[j]); checkTimer.Stop(); swApp.CloseAllDocuments(true); modelNames.RemoveAt(0); //removes as the very last step to ensure successful execution } catch (Exception e) { /* * Process swProcess = new Process(); * int processID = swApp.GetProcessID(); * swProcess = Process.GetProcessById(processID); * swProcess.Kill(); * while (swProcess.HasExited == false) { } */ checkTimer.Stop(); swApp = null; try { Process.Kill(); } catch { } Debug.Print("Solidworks Crash: Restarting Now"); Console.WriteLine("Solidworks Crash: Restarting Now"); Debug.Print(e.StackTrace); while (swApp == null) { Tuple <SldWorks, Process> tuple = GetSolidworks.Solidworks(1); swApp = tuple.Item1; Process = tuple.Item2; } } } swApp.Visible = true; swApp.SendMsgToUser2("Pack and Go Is Complete!", 2, 2); }
public void Dispose() { Assert.True(SwApp.CloseAllDocuments(true)); }
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(); }
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); }
/// <summary> /// 当结果返回True 时 表示两个零件不一样,结果false时表示 两个零件一样 /// </summary> /// <param name="sendTocustomer"></param> /// <param name="localModel"></param> /// <returns></returns> public bool CheckTwoParts(string sendTocustomer, string localModel) { bool different1 = false; bool different2 = false; swApp = ConnectToSolidWorks(); // swApp = ConnectToSolidWorks(); //加载参考关系零件 swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, (int)swLoadExternalReferences_e.swLoadExternalReferences_ChangedOnly); //后台模式 前台不显示界面 swApp.EnableBackgroundProcessing = true; //禁止记录文件路径 swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, true); swApp.OpenDoc(localModel, 1); swApp.OpenDoc(sendTocustomer, 1); ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc; string LocalPath = System.IO.Directory.GetParent(swModel.GetPathName()).ToString(); string tempAssembly = swApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateAssembly); AssemblyDoc assemblyDoc = (AssemblyDoc)swApp.NewDocument(tempAssembly, 0, 0, 0); Component2 insertComponentSendtoCustomer = assemblyDoc.AddComponent5(sendTocustomer, 0, "", false, "", 0, 0, 0); Component2 insertComponentLocal = assemblyDoc.AddComponent5(localModel, 0, "", false, "", 0, 0, 0); string sendSelect = insertComponentSendtoCustomer.GetSelectByIDString(); string localSelect = insertComponentLocal.GetSelectByIDString(); swModel = (ModelDoc2)swApp.ActiveDoc; bool b1 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + sendSelect, "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0); bool b2 = swModel.Extension.SelectByID2("Point1@Origin" + "@" + localSelect, "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0); int longstatus; Mate2 mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0.001, 0.001, 0.001, 0.001, 0, 0, 0, false, false, 0, out longstatus); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.SaveAs(LocalPath + @"\TopCheck.sldasm"); //不显示特征树 //swModel.Extension.HideFeatureManager(true); swModel.ClearSelection2(true); //swModel.FeatureManager.ViewFeatures = false; //FeatureManager featureManager = swModel.FeatureManager; //禁用特征树 //featureManager.EnableFeatureTree = false; // swModel.FeatureManager.EnableFeatureTreeWindow = false; #region first join Component2 sendToCustomerBodies = default(Component2); List <Component2> sendToCustomerBodiesList = new List <Component2>(); object swFaceOrPlane = default(object); assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out sendToCustomerBodies); sendToCustomerBodies.Select(true); assemblyDoc.FixComponent(); sendToCustomerBodies.Select(true); assemblyDoc.EditPart(); insertComponentSendtoCustomer.Select(false); insertComponentLocal.Select(true); assemblyDoc.InsertJoin2(false, false); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.BreakAllExternalReferences(); object[] splits = sendToCustomerBodies.Name2.Split('^'); // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0]; string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "localBodies-1"; ModelDoc2 compModel = default(ModelDoc2); compModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc(); if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART) { compName = compName + ".sldprt"; } else { compName = compName + ".sldasm"; } bool ret; ret = sendToCustomerBodies.SaveVirtualComponent(compName); sendToCustomerBodiesList.Add(sendToCustomerBodies); insertComponentSendtoCustomer.Select(false); swModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc2(); #region 获取所有零件中的零件,每一个实体做一次反切 List <string> bodyNamesCustomer = new List <string>(); PartDoc swPart = null; object vBody; swPart = (PartDoc)swModel; // Solid bodies object[] vBodyArr = null; Body2 swBody = default(Body2); MathTransform swMathTrans = null; vBodyArr = (object[])swPart.GetBodies2((int)swBodyType_e.swSolidBody, true); if ((vBodyArr != null)) { // Debug.Print(" Number of solid bodies: " + vBodyArr.Length); foreach (object vBody_loopVariable in vBodyArr) { vBody = vBody_loopVariable; swBody = (Body2)vBody; string[] vConfigName = null; vConfigName = (string[])swModel.GetConfigurationNames(); string sMatDB = ""; string sMatName = swBody.GetMaterialPropertyName("", out sMatDB); //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName)); //Debug.Print("Body--> " + swBody.Name + " " + ""); bodyNamesCustomer.Add(swBody.Name); } } //如果实体数量大于1,则继续新建对应数量的join 实体。 OnlyKeepNamedBody(bodyNamesCustomer[0], sendToCustomerBodies.GetSelectByIDString(), assemblyDoc, sendToCustomerBodies, insertComponentSendtoCustomer, ref different1); if (bodyNamesCustomer.Count > 1) { assemblyDoc.EditAssembly(); for (int i = 0; i < bodyNamesCustomer.Count - 1; i++) { Component2 returnpart = default(Component2); var partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "localBodies-" + (i + 2), out returnpart); sendToCustomerBodiesList.Add(returnpart); OnlyKeepNamedBody(bodyNamesCustomer[i + 1], partSelect, assemblyDoc, returnpart, insertComponentSendtoCustomer, ref different1); } } // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0) //Dim myFeature As Object //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True) #endregion 获取所有零件中的零件,每一个实体做一次反切 //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); Feature theFeature; //theFeature = swModel.FeatureByPositionReverse(0); //if (theFeature.Name.Contains("Cavity")) //{ // //theFeature.Select(true); // swModel = (ModelDoc2)swApp.ActiveDoc; // bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); // swModel.BreakAllExternalReferences(); // different1 = true; // //JoinPart1 留下的: 发给客户的没有此部分。 而本地零件中有 //} //else //{ // //无法Join时表示 全切了。 // swModel = (ModelDoc2)swApp.ActiveDoc; // bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); // swModel.EditSuppress(); //} //sendToCustomerBodies.Select(true); assemblyDoc.EditAssembly(); #endregion first join #region sercond join2 Component2 localBodies = default(Component2); List <Component2> LocalBodiesList = new List <Component2>(); assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out localBodies); localBodies.Select(true); assemblyDoc.FixComponent(); localBodies.Select(true); assemblyDoc.EditPart(); insertComponentSendtoCustomer.Select(false); insertComponentLocal.Select(true); assemblyDoc.InsertJoin2(false, false); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.BreakAllExternalReferences(); splits = localBodies.Name2.Split('^'); // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0]; compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "sendToCustomerBodies-1"; compModel = default(ModelDoc2); compModel = (ModelDoc2)localBodies.GetModelDoc(); if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART) { compName = compName + ".sldprt"; } else { compName = compName + ".sldasm"; } ret = localBodies.SaveVirtualComponent(compName); LocalBodiesList.Add(localBodies); insertComponentLocal.Select(false); swModel = (ModelDoc2)localBodies.GetModelDoc2(); #region 获取所有零件中的零件,每一个实体做一次反切 List <string> bodyNamesLocal = new List <string>(); PartDoc swPart2 = null; object vBody2; swPart2 = (PartDoc)swModel; // Solid bodies object[] vBodyArr2 = null; Body2 swBody2 = default(Body2); MathTransform swMathTrans2 = null; vBodyArr2 = (object[])swPart2.GetBodies2((int)swBodyType_e.swSolidBody, true); if ((vBodyArr2 != null)) { // Debug.Print(" Number of solid bodies: " + vBodyArr.Length); foreach (object vBody_loopVariable in vBodyArr2) { vBody2 = vBody_loopVariable; swBody2 = (Body2)vBody2; string[] vConfigName = null; vConfigName = (string[])swModel.GetConfigurationNames(); string sMatDB = ""; string sMatName = swBody2.GetMaterialPropertyName("", out sMatDB); //bRet = swBody.RemoveMaterialProperty((int)swInConfigurationOpts_e.swAllConfiguration, (vConfigName)); bodyNamesLocal.Add(swBody2.Name); } } //如果实体数量大于1,则继续新建对应数量的join 实体。 OnlyKeepNamedBody(bodyNamesLocal[0], localBodies.GetSelectByIDString(), assemblyDoc, localBodies, insertComponentLocal, ref different2); if (bodyNamesLocal.Count > 1) { assemblyDoc.EditAssembly(); for (int i = 0; i < bodyNamesLocal.Count - 1; i++) { Component2 returnpart = default(Component2); var partSelect = CreateNewJoinPart(assemblyDoc, insertComponentSendtoCustomer, insertComponentLocal, swModel, "sendToCustomerBodies-" + (i + 2), out returnpart); LocalBodiesList.Add(returnpart); OnlyKeepNamedBody(bodyNamesLocal[i + 1], partSelect, assemblyDoc, returnpart, insertComponentLocal, ref different2); } } // boolstatus = Part.Extension.SelectByID2("Join1[2]@localBodies-1@TopCheck", "SOLIDBODY", 0, 0, 0, True, 0, Nothing, 0) //Dim myFeature As Object //Set myFeature = Part.FeatureManager.InsertDeleteBody2(True) #endregion 获取所有零件中的零件,每一个实体做一次反切 //assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); //theFeature = swModel.FeatureByPositionReverse(0); //swModel = (ModelDoc2)localBodies.GetModelDoc2(); //theFeature = swModel.FeatureByPositionReverse(0); //if (theFeature.Name.Contains("Cavity")) //{ // //theFeature.Select(true); // swModel = (ModelDoc2)swApp.ActiveDoc; // bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + localBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); // swModel.BreakAllExternalReferences(); // different2 = true; // //JoinPart2 留下的: 发给客户的有此部分。 而本地零件中没有 //} //else //{ // //无法Join时表示 全切了。 // swModel = (ModelDoc2)swApp.ActiveDoc; // bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + sendToCustomerBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); // swModel.EditSuppress(); //} //localBodies.Select(true); //assemblyDoc.EditAssembly(); #endregion sercond join2 #region joinPartPublic Component2 publicBodies = default(Component2); assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out publicBodies); publicBodies.Select(true); assemblyDoc.FixComponent(); publicBodies.Select(true); assemblyDoc.EditPart(); insertComponentSendtoCustomer.Select(false); insertComponentLocal.Select(true); assemblyDoc.InsertJoin2(false, false); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.BreakAllExternalReferences(); splits = publicBodies.Name2.Split('^'); // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0]; compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + "publicBodies"; compModel = default(ModelDoc2); compModel = (ModelDoc2)publicBodies.GetModelDoc(); if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART) { compName = compName + ".sldprt"; } else { compName = compName + ".sldasm"; } ret = publicBodies.SaveVirtualComponent(compName); swModel.ClearSelection(); foreach (var item in sendToCustomerBodiesList) { item.Select(false); assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); theFeature = (Feature)swModel.FeatureByPositionReverse(0); swModel = (ModelDoc2)publicBodies.GetModelDoc2(); theFeature = (Feature)swModel.FeatureByPositionReverse(0); if (theFeature.Name.Contains("Cavity")) { //theFeature.Select(true); swModel = (ModelDoc2)swApp.ActiveDoc; bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); swModel.BreakAllExternalReferences(); //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有 } else { } } foreach (var item in LocalBodiesList) { item.Select(false); assemblyDoc.InsertCavity4(0, 0, 0, true, 1, -1); theFeature = (Feature)swModel.FeatureByPositionReverse(0); swModel = (ModelDoc2)publicBodies.GetModelDoc2(); theFeature = (Feature)swModel.FeatureByPositionReverse(0); if (theFeature.Name.Contains("Cavity")) { //theFeature.Select(true); swModel = (ModelDoc2)swApp.ActiveDoc; bool b = swModel.Extension.SelectByID2(theFeature.Name + "@" + publicBodies.GetSelectByIDString(), "BODYFEATURE", 0, 0, 0, false, 0, null, 0); swModel.BreakAllExternalReferences(); //joinPartPublic 留下的: 发给客户的有此部分。 而本地零件中没有 } else { } } publicBodies.Select(true); assemblyDoc.EditAssembly(); #endregion joinPartPublic foreach (var item in sendToCustomerBodiesList) { item.Select(false); setColour(Color.Red); } foreach (var item in LocalBodiesList) { item.Select(false); setColour(Color.Blue); } swModel = (ModelDoc2)swApp.ActiveDoc; swModel.ClearSelection2(true); insertComponentLocal.Select(false); insertComponentSendtoCustomer.Select(true); swModel.HideComponent2(); swModel.ClearSelection2(true); publicBodies.Select(false); assemblyDoc.SetComponentTransparent(true); setColour(Color.Green); swModel.EditRebuild3(); swModel.Save(); swModel.SaveAs3(LocalPath + @"\01_CheckResult.sldprt", 0, 0); swApp.CloseDoc("TopCheck.sldasm"); swApp.CloseAllDocuments(true); swApp.OpenDoc(LocalPath + @"\01_CheckResult.sldprt", 1); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.ShowNamedView2("*Isometric", 7); swModel.ViewZoomtofit2(); swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, false); try { System.IO.File.Delete(LocalPath + @"\TopCheck.sldasm"); System.IO.File.Delete(LocalPath + @"\localBodies.sldprt"); System.IO.File.Delete(LocalPath + @"\sendToCustomerBodies.sldprt"); System.IO.File.Delete(LocalPath + @"\publicBodies.sldprt"); } catch (Exception) { } //第二次反向剪切 swApp.CloseDoc(sendTocustomer); swApp.CloseDoc(localModel); swModel.FeatureManager.EnableFeatureTree = true; swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swLoadExternalReferences, 2); if (different1 == false && different2 == false) { return(false); } else { return(true); } }
/// <summary> /// 重置SldWorks对象,放回连接池时调用 /// </summary> /// <param name="sldWorks">要放入池中的对象</param> private void ResetSolidWorks(SldWorks sldWorks) { // 重置SldWorks对象的操作,便于下次使用 sldWorks.CloseAllDocuments(true); //sldWorks.Visible = false; }