public SolidWorksComponent() { Debug.Print("{0} - *********************************************************************************************", DateTime.Now.ToLongTimeString()); Debug.Print("{0} - new()", DateTime.Now.ToLongTimeString()); //Checks.SW_Open() try { swApp=new SldWorks.SldWorks(); swModel=swApp.ActiveDoc; if (swModel == null) { Debug.Print("{0} - No file openned", DateTime.Now.ToLongTimeString()); } else if (swModel.GetType() == swDocumentTypes_e.swDocASSEMBLY.GetHashCode() | swModel.GetType() == swDocumentTypes_e.swDocPART.GetHashCode()) { } else { Debug.Print("{0} - no file compatible", DateTime.Now.ToLongTimeString()); } } catch (System.Exception ex) { Debug.Print("{0} - ERROR : {1}", DateTime.Now.ToLongTimeString(),ex.ToString()); } }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); var part = (ModelDoc2)swInstance.ActiveDoc; var drawing = (DrawingDoc)part; var boolStatus = drawing.ActivateView("Drawing View1"); boolStatus = part.Extension.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); var autoballonParameters = drawing.CreateAutoBalloonOptions(); autoballonParameters.Layout = (int)swBalloonLayoutType_e.swDetailingBalloonLayout_Square; autoballonParameters.ReverseDirection = false; autoballonParameters.IgnoreMultiple = true; autoballonParameters.InsertMagneticLine = true; autoballonParameters.LeaderAttachmentToFaces = true; autoballonParameters.Style = (int)swBalloonStyle_e.swBS_Box; autoballonParameters.Size = (int)swBalloonFit_e.swBF_2Chars; autoballonParameters.UpperTextContent = (int)swBalloonTextContent_e.swBalloonTextItemNumber; autoballonParameters.Layername = "Format"; autoballonParameters.ItemNumberStart = 1; autoballonParameters.ItemNumberIncrement = 1; autoballonParameters.ItemOrder = (int)swBalloonItemNumbersOrder_e.swBalloonItemNumbers_DoNotChangeItemNumbers; autoballonParameters.EditBalloons = true; autoballonParameters.EditBalloonOption = (int)swEditBalloonOption_e.swEditBalloonOption_Resequence; var vNotes = drawing.AutoBalloon5(autoballonParameters); }
private void button1_Click(object sender, EventArgs e) { swApp = SolidWorksSingleton.Get_swApp(); swModel = swApp.ActiveDoc; var arquivo = new Arquivo(); int[] codigos = Enumerable.Range(4020128, 2).ToArray(); for (int i = 0; i < codigos.Length - 1; i++) { txtCodigo.Text = codigos[i].ToString(); swApp.OpenDoc(@"C:\ELETROFRIO\ENGENHARIA SMR\PRODUTOS FINAIS ELETROFRIO\MECÂNICA\RACK PADRAO\template_00_rp.SLDASM", (int)swDocumentTypes_e.swDocASSEMBLY); swModel = swApp.ActiveDoc; swView = swModel.ActiveView; swView.EnableGraphicsUpdate = false; // Chamar montador e passar codigo do kit string codigo = codigos[i].ToString(); Montador.MontarKit(codigo); swModel = swApp.ActiveDoc; swExt = swModel.Extension; swApp.DocumentVisible(true, (int)swDocumentTypes_e.swDocASSEMBLY); swApp.DocumentVisible(true, (int)swDocumentTypes_e.swDocPART); string fullPath = @"C:\ELETROFRIO\ENGENHARIA SMR\PRODUTOS FINAIS ELETROFRIO\MECÂNICA\RACK PADRAO\RACK PADRAO TESTE\" + codigo + ".sldasm"; swExt.Rebuild((int)swRebuildOptions_e.swUpdateMates); swModel.SaveAs(fullPath); swApp.CloseDoc(fullPath); } swView.EnableGraphicsUpdate = true; }
private Boolean connectToSolidWorks() { if (swApp == null) { alreadyOpen = false; try { swApp = System.Runtime.InteropServices.Marshal.GetActiveObject(progID) as SldWorks.SldWorks; swApp.Visible = true; alreadyOpen = true; } catch { } if (!alreadyOpen) { Type swAppType = System.Type.GetTypeFromProgID(progID); swApp = System.Activator.CreateInstance(swAppType) as SldWorks.SldWorks; swApp.Visible = true; } } if (swApp != null) { swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, true); } return(true); }
private void Button_Click(object sender, RoutedEventArgs e) { //Solidworksのプロセス起動 swApp = new SldWorks.SldWorks(); //画面を表示する falseなら裏で動作 swApp.Visible = true; string fileName = null; OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "step(*.step)|*.step;*.stp|parasolid(*.x_t)|*.x_t"; if (ofd.ShowDialog() == true) { fileName = ofd.FileName; } else { return; } PARTNAME = fileName.Substring(fileName.LastIndexOf(@"\") + 1); //新規モデルの読み込み bool bRet = false; string strArg = null; ImportStepData importData = default(ImportStepData); int Err = 0; //fileName = DIR+"v1_4.step"; importData = swApp.GetImportFileData(fileName); swModel = swApp.LoadFile4(fileName, strArg, importData, ref Err); }
private void Button_Click_5(object sender, RoutedEventArgs e) { if (swApp != null) { swApp.ExitApp(); swApp = null; } }
public static void GetApp() { App = (SldWorks.SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application")); if (App == null) { KKS.KKS_Message.Show("Kein SWX am laufen"); SWX.Settings.Run = false; } }
/// <summary> /// Creates an instance of SolidWorks class /// </summary> /// <param name="version">Information about a version in SWVersion class format.</param> public SolidWorks(SWVersion version) { rotTimer = new Timer(); rotTimer.Elapsed += UpdateROT; _ROT = ROTHelper.GetActiveObjectList(String.Empty); _instance = null; swProcess = null; swVersion = version; ProcessEnded += ProcessHasEnded; }
static void Main(string[] args) { WiseUtil wiseUtil = new WiseUtil(); string installLocation = wiseUtil.GetLocalMachineRegistryValue("SOFTWARE\\solidworks\\Applications\\PDMWorks Enterprise\\", "Location"); System.Console.WriteLine(installLocation); if (installLocation == "") { installLocation = "C:\\"; } string excelTemplate = installLocation + "ExportTemplate\\template-list.xlsx"; Workbook templateWb = wiseUtil.OpenExcel(excelTemplate); SldWorks.SldWorks swApp; //IEdmVault5 vault = new EdmVault5(); //vault.LoginAuto("科德研发部"); swApp = new SldWorks.SldWorks(); int longstatus = 0; int longwarnings = 0; //E:\\wisevault0\\draw\\G20-A01P.SLDDRW //F:\\科德研发部\\01-机床整机产品\\01-铣车复合机\\KMC800 系列机型\\02-裸机图纸\\KMC800\\710.14 滑枕组件\\710.1401 滑枕组件装配图基础 A2.SLDDRW ModelDoc2 modelDoc = swApp.OpenDoc6("E:\\wisevault0\\draw\\G20-A01P.SLDDRW", (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, "", ref longstatus, ref longwarnings); BomTableAnnotation bomTableAnno; string configName = ""; string topFileName = ""; wiseUtil.GetDrawingDocBOMTable(modelDoc, out bomTableAnno, out configName, out topFileName); //modelDoc.Close(); IEdmVault5 poVault = null; SldAsm asmPrd = wiseUtil.GetAsmIndoFromFile(poVault, topFileName);// new SldAsm(); if (asmPrd == null) { return(false); } //asmPrd.bzr = "hou"; //asmPrd.bzsj = "2016/1/1"; wiseUtil.ProcessTableAnn(poVault, bomTableAnno, configName, asmPrd); asmPrd.bzr = "hou"; asmPrd.bzsj = "2016/1/1"; wiseUtil.ProcessTableAnn(bomTableAnno, configName, asmPrd); wiseUtil.SaveBuyToWorkbook(templateWb, asmPrd); wiseUtil.SaveStdToWorkbook(templateWb, asmPrd); wiseUtil.SavePrtToWorkbook(templateWb, asmPrd); templateWb.SaveAs("D:\\a.xlsx"); templateWb.Close(); swApp.ExitApp(); swApp = null; }
public Form1() { InitializeComponent(); try { swApp = (SldWorks.SldWorks)Marshal.GetActiveObject("SldWorks.Application"); } catch (Exception) { swApp = new SldWorks.SldWorks(); swApp.Visible = true; } }
// Verbindet mit SolidWorks private void b_startSLDWorks_Click(object sender, EventArgs e) { try { swApp = (SldWorks.SldWorks)Marshal.GetActiveObject("SldWorks.Application"); } catch (Exception) { swApp = new SldWorks.SldWorks(); swApp.Visible = true; } }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); var model = (ModelDoc2)swInstance.ActiveDoc; model.ForceRebuild3(true); var delay = 300; Thread.Sleep(delay); model.ForceRebuild3(true); }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); var model = (ModelDoc2)swInstance.ActiveDoc; var drawing = (DrawingDoc)model; var docExtension = (ModelDocExtension)model.Extension; drawing.ActivateView("Drawing View1"); var activeView = (View)drawing.ActiveDrawingView; activeView.AutoInsertCenterMarks2(7, 11, true, true, true, 0.002, 0.0025, true, true, 0); }
void IDisposable.Dispose() { try { _app.CloseAllDocuments(true); _app.ExitApp(); _app = null; } // ReSharper disable EmptyGeneralCatchClause catch { } // ReSharper restore EmptyGeneralCatchClause }
private void contact_SW_Click(object sender, EventArgs e) { try { swApp = (SldWorks.SldWorks)Marshal.GetActiveObject("SldWorks.Application"); } catch (Exception) { swApp = new SldWorks.SldWorks(); } swApp.Visible = true; MessageBox.Show("Verbindung zu SolidWorks hergestellt."); }
private void m_startSolidworksButton_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { m_swApp = new SldWorks.SldWorks(); m_swApp.Visible = true; } catch { } finally { this.Cursor = Cursors.Default; } }
private void m_closeSolidworksButton_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { m_swApp.ExitApp(); m_swApp = null; } catch { } finally { this.Cursor = Cursors.Default; } }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); var model = (ModelDoc2)swInstance.ActiveDoc; var drawing = (DrawingDoc)swInstance.ActiveDoc; // read app data to get the path of the drawing config file to read var appDataPath = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\app data\rebuild.txt"; var appDataLines = System.IO.File.ReadAllLines(appDataPath); // references: "C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\base blob - L1\blob.coverDrawing.txt" var configPath = appDataLines[0]; var configLines = System.IO.File.ReadAllLines(configPath); // get requested drawing view scale value from config var drawingView1ScaleString = configLines[0].Split('=')[1].Trim(); var drawingView1ScaleArray = new double[2]; drawingView1ScaleArray[0] = Double.Parse(drawingView1ScaleString.ToCharArray()[0] + ""); drawingView1ScaleArray[1] = Double.Parse(drawingView1ScaleString.ToCharArray()[2] + ""); var drawingView1Scale = drawingView1ScaleArray[0] / drawingView1ScaleArray[1]; // get drawing active view sheet var activeView = (View)drawing.GetFirstView(); // get first drawing view activeView = (View)activeView.GetNextView(); // set View::ScaleRatio value activeView.ScaleDecimal = drawingView1Scale; // get reference to Drawing View2 activeView = (View)activeView.GetNextView(); // set if not null if (activeView != null) { activeView.ScaleDecimal = drawingView1Scale; } // rebuild to reflect changes model.EditRebuild3(); }
// Closes Solidworks with/without a messagebox prompt to confirm public void CloseSolidworks(bool withPrompt) { if (withPrompt) { if (MessageBox.Show("Ok to close Solidworks?", "Close Solidworks", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3, MessageBoxOptions.DefaultDesktopOnly) == DialogResult.Yes) { } } Console.Write("\nExiting... "); if (swApp == null) { ShowNonFatalError("Solidworks isn't open, can't close it."); return; } swApp.ExitApp(); swApp = null; Console.Write("Exited Solidworks.\n"); }
static void Main() { swApp = SwApp.Instance; // Get SolidWorks swApp.Visible = true; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Launcher lcher = new Launcher(); Logger.Info("SolidCompare Started"); Application.Run(lcher); Logger.Info("Launcher closed."); string dir1 = lcher.directory1; string dir2 = lcher.directory2; report = new Reporter(SwApp.StripFile(dir1)); List <ModelDoc2> previousDocs = SwApp.ListCurrentlyOpened(); Assembly refAssembly = new Assembly((IAssemblyDoc)SwApp.OpenFile(dir1)); Assembly modAssembly = new Assembly((IAssemblyDoc)SwApp.OpenFile(dir2)); report.AddComparison(refAssembly.Title, modAssembly.Title); CompareResult compareResult = refAssembly.CompareTo(modAssembly); Console.WriteLine(compareResult); report.AddSection("Assembly Comparison"); report.AddSubSection("Reported Changes"); report.AddLine(compareResult.ToString()); report.AddSection("Volumetric Comparison"); report.PrintDelayed(); Logger.EndReport(); SwApp.Cleanup(previousDocs); MessageBox.Show("Done"); }
private void releaseSolidWorks() { if (swApp != null) { swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swLockRecentDocumentsList, false); } if (!alreadyOpen) { try { swApp.CloseAllDocuments(true); swApp.ExitApp(); } catch { } } GC.Collect(); swApp = null; }
// "Open solidworks" button private void button3_Click(object sender, EventArgs e) { // Open Solidworks Console.WriteLine("Opening Solidworks.exe ..."); swApp = new SldWorks.SldWorks(); // swApp.Visible = true; // If any parts are open, notify and exit script if (swApp.ActiveDoc != null) { Console.WriteLine("Solidworks already open, restarting it..."); CloseSolidworks(false); // Close without prompt button3_Click(null, null); return; } else { Console.WriteLine("Opened Solidworks.exe successfully."); startSolidworks.Enabled = false; // Disable the "Start Solidworks form button" } }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); var model = (ModelDoc2)swInstance.ActiveDoc; // read from app data file var appDataPath = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\app data\rebuild.txt"; var appDataLines = System.IO.File.ReadAllLines(appDataPath); // read from config path var configPath = appDataLines[0]; var configLines = System.IO.File.ReadAllLines(configPath); // generate property value dictionary var propertyValueDict = new Dictionary <string, string>(); foreach (string line in configLines) { if (line.Contains("Property")) { var property = line.Split(':')[1].Split('=')[0].Replace("\"", "").Trim(); var value = line.Split('=')[1].Trim(); propertyValueDict.Add(property, value); } } // set custom property data var modelExtension = (ModelDocExtension)model.Extension; var customPropertyManager = modelExtension.CustomPropertyManager[""]; foreach (string property in propertyValueDict.Keys) { customPropertyManager.Set2(property, propertyValueDict[property]); } model.ForceRebuild3(true); }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); var model = (ModelDoc2)swInstance.ActiveDoc; // read rebuild.txt to get the config.txt file path var rebuildAppDataPath = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\app data\rebuild.txt"; var configPath = @System.IO.File.ReadAllLines(rebuildAppDataPath)[0]; // get material value from config.txt file var configLines = System.IO.File.ReadAllLines(configPath); var material = ""; foreach (string line in configLines) { if (line.Contains("Material")) { material = line.Split('=')[1].Trim(); } } // populate material dictionary - by hand for now var materialDict = new Dictionary <string, string>(); materialDict.Add("0", "ASTM A36 Steel"); materialDict.Add("1", "6061 Alloy"); // allow user to select material via a variable in config.txt file for *.SLDPRT files - intended for covers only atm var partDoc = (PartDoc)model; var materialDatabases = swInstance.GetMaterialDatabases(); var db = (string)materialDatabases[3]; // set material property on active doc - DOES NOT currently check to see if the appropriate doc is currently active partDoc.SetMaterialPropertyName(db, materialDict[material]); }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); var model = (ModelDoc2)swInstance.ActiveDoc; var matesToFlip = new string[] { }; // read rebuil.txt app data file var rebuildAppDataPath = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\app data\rebuild.txt"; var rebuildAppDataLines = System.IO.File.ReadAllLines(rebuildAppDataPath); var assemblyConfigPath = rebuildAppDataLines[0]; var assemblyConfigLines = System.IO.File.ReadAllLines(assemblyConfigPath); // get correlated X/Z negation state for hole # and affect X or Z values // for that hole number flip the negation state on the assembly config file // up to both the X and Z values for that hole number can be flipped var holeNumber = ""; var flipX = false; var flipZ = false; foreach (string appDataLine in rebuildAppDataLines) { foreach (string line in assemblyConfigLines) { if (line.Contains(appDataLine) && !flipX) { if (line.Contains("X")) { flipX = true; holeNumber = line.Split('=')[1].Split(' ')[2].Trim(); } } if (line.Contains(appDataLine) && !flipZ) { if (line.Contains("Z")) { flipZ = true; holeNumber = line.Split('=')[1].Split(' ')[2].Trim(); } } } } // read assembly file and generate the flipped negation state output if (flipX || flipZ) { for (var i = 0; i < assemblyConfigLines.Length; ++i) { if (assemblyConfigLines[i].Contains("Negative")) { if (flipX && assemblyConfigLines[i].Contains("X")) { var lineSegments = assemblyConfigLines[i].Split('='); var currentState = lineSegments[1]; var newLine = lineSegments[0] + "= " + (currentState.Contains("1") ? "0" : "1"); assemblyConfigLines[i] = newLine; } else if (flipZ && assemblyConfigLines[i].Contains("Z")) { var lineSegments = assemblyConfigLines[i].Split('='); var currentState = lineSegments[1]; var newLine = lineSegments[0] + "= " + (currentState.Contains("1") ? "0" : "1"); assemblyConfigLines[i] = newLine; } } } } // write to assembly file var builder = ""; foreach (string line in assemblyConfigLines) { builder += line + "\n"; } System.IO.File.WriteAllText(assemblyConfigPath, builder); // if rebuild app data contains a dimension list - creates a new array for the mates that need to be flipped if (rebuildAppDataLines.Length >= 2) { if (rebuildAppDataLines[1].Contains("Distance")) { matesToFlip = new string[rebuildAppDataLines.Length - 1]; for (var i = 1; i < rebuildAppDataLines.Length; ++i) { matesToFlip[i - 1] = rebuildAppDataLines[i]; } // flips the mate if the X/Z offset is negative relative to current position var cutOff = 5_000; var firstFeature = (Feature)model.FirstFeature(); while (firstFeature != null && cutOff-- > 0) { if ("MateGroup" == firstFeature.GetTypeName()) { var mateGroup = (Feature)firstFeature.GetFirstSubFeature(); var index = 0; while (mateGroup != null) { var mate = (Mate2)mateGroup.GetSpecificFeature2(); var mateName = mateGroup.Name; foreach (string dimension in matesToFlip) { if (dimension == mateName) { mate.Flipped = !mate.Flipped; } } mateGroup = (Feature)mateGroup.GetNextSubFeature(); ++index; } } firstFeature = (Feature)firstFeature.GetNextFeature(); } // remove the listed mates so it doesn't flip them again System.IO.File.WriteAllText(rebuildAppDataPath, assemblyConfigPath); } } model.ForceRebuild3(true); Thread.Sleep(500); model.ForceRebuild3(true); }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); var model = (ModelDoc2)swInstance.ActiveDoc; var isDebug = false; // read rebuild.txt var rebuildPath = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\app data\rebuild.txt"; var partConfigPath = System.IO.File.ReadAllLines(rebuildPath)[0]; // read contents of config file var partConfigLines = System.IO.File.ReadAllLines(partConfigPath); // (prefix, dimension negative state) - both can be either negative or positive // (-, -) write positive/rebuild/write positive/(unconfirmed)write negative state // (-, +) write negative/rebuild/write positive/(unconfirmed)write negative state // (+, -) write negative/rebuild/write positive/(unconfirmed)write positive state // (+, +) write positive/rebuild/write positive/write positive state // populate variable/line number dict var variableLineNumberDict = new Dictionary <int, string>(); var negativeStateString = ""; var index = 0; foreach (string line in partConfigLines) { if (line.Contains("in") && line.Contains("Offset")) { variableLineNumberDict.Add(index, line); } if (line.Contains("Negative")) { negativeStateString += line + "$"; } ++index; } var negativeStateArray = negativeStateString.Split('$'); // populate line number/negative state dict // do so by inputing the corresponding line variable number and // if its negative state variable is negative var lineNumberNegativeStateDict = new Dictionary <int, string>(); //(<#>, (<"-" | "+">, <"-" | "+">)) foreach (int lineNumber in variableLineNumberDict.Keys) { foreach (string negativeState in negativeStateArray) { if (negativeState.Length > 0) { var negativeStateHoleNumber = ""; var negativeStateXZ = ""; var negativeStateSegments = negativeState.Split(' '); if (negativeState.Contains("Handle")) { negativeStateHoleNumber = negativeStateSegments[2].Trim() + " " + negativeStateSegments[3].Trim(); negativeStateXZ = negativeStateSegments[4].Trim(); } else { negativeStateHoleNumber = "Hole " + negativeStateSegments[1].Trim(); negativeStateXZ = negativeStateSegments[3].Trim(); } if (variableLineNumberDict[lineNumber].Contains(negativeStateHoleNumber) && variableLineNumberDict[lineNumber].Contains(negativeStateXZ)) { var negativeStateIsNegative = false; if (negativeState.Contains("Handle")) { negativeStateIsNegative = negativeState.Split('=')[1].Contains("1"); } else { negativeStateIsNegative = negativeStateSegments[5].Trim() .Contains("1"); } var lineIsNegative = variableLineNumberDict[lineNumber].Contains("-"); var lineState = (lineIsNegative ? "-" : "+") + " " + (negativeStateIsNegative ? "-" : "+"); if (!lineNumberNegativeStateDict.ContainsKey(lineNumber)) { lineNumberNegativeStateDict.Add(lineNumber, lineState); } } } } } // generate first write config lines foreach (int lineNumber in lineNumberNegativeStateDict.Keys) { var state = lineNumberNegativeStateDict[lineNumber]; var newLine = ""; switch (state) { case "- -": // write positive/rebuild/write positive newLine = partConfigLines[lineNumber].Replace("-", ""); partConfigLines[lineNumber] = newLine; break; case "- +": // write negative/rebuild/write positive break; case "+ -": // write negative/rebuild/write positive var equalIndex = partConfigLines[lineNumber].IndexOf('='); newLine = partConfigLines[lineNumber].Insert(equalIndex + 2, "-"); partConfigLines[lineNumber] = newLine; break; case "+ +": break; } } // first write var builder = ""; foreach (string line in partConfigLines) { builder += line + "\n"; } if (!isDebug) { System.IO.File.WriteAllText(partConfigPath, builder); } // wait a moment if (!isDebug) { Thread.Sleep(500); } // rebuild if (!isDebug) { model.ForceRebuild3(true); } // wait a moment if (!isDebug) { Thread.Sleep(500); } // populate negation variable line number dict var lineNumberNegationStateLineNumberDict = new Dictionary <int, int>(); foreach (int lineNumber in variableLineNumberDict.Keys) { var partConfigLine = partConfigLines[lineNumber]; var lineSegments = variableLineNumberDict[lineNumber].Split(' '); var lineHoleNumber = ""; var lineXZ = ""; if (partConfigLine.Contains("Handle")) { var partConfigLineSegments = partConfigLine.Split(' '); lineHoleNumber = partConfigLineSegments[2].Trim() + " " + partConfigLineSegments[3].Trim(); lineXZ = partConfigLineSegments[4].Trim(); } else { lineHoleNumber = "Hole " + lineSegments[1]; lineXZ = lineSegments[3]; } index = 0; foreach (string line in partConfigLines) { if (line.Contains(lineHoleNumber) && line.Contains(lineXZ) && line.Contains("Negative")) { if (!lineNumberNegationStateLineNumberDict.ContainsKey(lineNumber)) { lineNumberNegationStateLineNumberDict.Add(lineNumber, index); } } ++index; } } // generate second write config lines // this daemon must write after a switch if a feature is now // in a negative quadrant foreach (int lineNumber in lineNumberNegativeStateDict.Keys) { var line = partConfigLines[lineNumber]; var state = lineNumberNegativeStateDict[lineNumber]; var newLine = ""; var negationLineNumber = 0; var newNegationLine = ""; switch (state) { case "- -": // write positive/rebuild/write positive break; // write positive state to negative case "- +": // write negative/rebuild/write positive/write negative state newLine = partConfigLines[lineNumber].Replace("-", ""); partConfigLines[lineNumber] = newLine; if (lineNumberNegationStateLineNumberDict.ContainsKey(lineNumber)) { negationLineNumber = lineNumberNegationStateLineNumberDict[lineNumber]; } var lineSegments = partConfigLines[negationLineNumber].Split('='); newNegationLine = lineSegments[0].Trim() + "= " + lineSegments[1].Trim().Replace('0', '1'); partConfigLines[negationLineNumber] = newNegationLine; break; // write negative state to positive case "+ -": // write negative/rebuild/write positive newLine = partConfigLines[lineNumber].Replace("-", ""); partConfigLines[lineNumber] = newLine; negationLineNumber = lineNumberNegationStateLineNumberDict[lineNumber]; var stateVariableIndex = partConfigLines[negationLineNumber].LastIndexOf('1'); newNegationLine = partConfigLines[negationLineNumber].Remove(stateVariableIndex, 1); newNegationLine += "0"; partConfigLines[negationLineNumber] = newNegationLine; break; case "+ +": break; } } // second write var secondBuilder = ""; foreach (string line in partConfigLines) { secondBuilder += line + "\n"; } if (!isDebug) { System.IO.File.WriteAllText(partConfigPath, secondBuilder); } }
public bool exportExcel(IEdmVault5 poVault, string selectFile, string saveFile) { WiseUtil wiseUtil = new WiseUtil(); IEdmFolder5 templateExcelFolder = null; string finalFilePath = poVault.RootFolderPath + WiseUtil.templateExcelFilePath; IEdmFile5 templateExcelFile = poVault.GetFileFromPath(finalFilePath, out templateExcelFolder); if (templateExcelFile == null) { System.Windows.Forms.MessageBox.Show("在PDM中找不到模板EXCEL:\n" + finalFilePath); return(false); } //string installLocation = wiseUtil.GetLocalMachineRegistryValue("SOFTWARE\\solidworks\\Applications\\PDMWorks Enterprise\\", "Location"); //System.Console.WriteLine(installLocation); //if (installLocation == "") //{ // installLocation = "C:\\"; //} //string excelTemplate = installLocation + "ExportTemplate\\template-list.xlsx"; Workbook templateWb = null; try { templateWb = wiseUtil.OpenExcel(finalFilePath); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("打开模板表格失败,请查看位置" + templateExcelFile + "的文件状态"); return(false); } if (templateWb == null) { System.Windows.Forms.MessageBox.Show("打开模板表格失败"); return(false); } SldWorks.SldWorks swApp = new SldWorks.SldWorks(); int longstatus = 0; int longwarnings = 0; ModelDoc2 modelDoc = swApp.OpenDoc6(selectFile, (int)swDocumentTypes_e.swDocDRAWING, (int)(swOpenDocOptions_e.swOpenDocOptions_ReadOnly | swOpenDocOptions_e.swOpenDocOptions_Silent), "", ref longstatus, ref longwarnings); if (modelDoc == null || longstatus > 0) { System.Windows.Forms.MessageBox.Show("打开二维图失败"); swApp.ExitApp(); templateWb.Close(); return(false); } BomTableAnnotation bomTableAnno = null; string configName = ""; string topFileName = ""; try { wiseUtil.GetDrawingDocBOMTable(modelDoc, out bomTableAnno, out configName, out topFileName); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("获取明细表信息出错" + e.StackTrace); } if (bomTableAnno == null) { System.Windows.Forms.MessageBox.Show("未找到明细表信息"); swApp.ExitApp(); templateWb.Close(); return(false); } //modelDoc.Close(); SldAsm asmPrd = wiseUtil.GetAsmIndoFromFile(poVault, topFileName);// new SldAsm(); if (asmPrd == null) { System.Windows.Forms.MessageBox.Show("获取材料明细表关联产品失败"); swApp.ExitApp(); templateWb.Close(); return(false); } //asmPrd.bzr = "hou"; //asmPrd.bzsj = "2016/1/1"; try { wiseUtil.ProcessTableAnn(poVault, bomTableAnno, configName, asmPrd); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("解析明细表信息出错" + e.StackTrace); } //if (WiseUtil.errors > 0) //{ // System.Windows.Forms.MessageBox.Show("解析明细表信息出错" + WiseUtil.errorStr); //} wiseUtil.SaveBuyToWorkbook(templateWb, asmPrd); wiseUtil.SaveStdToWorkbook(templateWb, asmPrd); wiseUtil.SavePrtToWorkbook(templateWb, asmPrd); wiseUtil.SaveBspToWorkbook(templateWb, asmPrd); templateWb.SaveAs(saveFile); templateWb.Close(); swApp.ExitApp(); swApp = null; return(true); }
private void button1_Click(object sender, EventArgs e) { try { swApp = (SldWorks.SldWorks)Marshal.GetActiveObject("SldWorks.application"); } catch { MessageBox.Show("Erro ao conectar no Solidworks"); return; } var excel = new Read_From_Excel(); // O metodo retorna uma lista de coletores List <Coletor> coletores = excel.getColetores(); // Converto a Lista retornada para array para acessar pelo indice. Array c = (coletores.ToArray()); //swApp.DocumentVisible(false, (int)swDocumentTypes_e.swDocNONE); for (int i = 0; i < c.Length; i++) { Coletor coletor = (Coletor)c.GetValue(i); string qtCP = coletor.QuantidadeCompressor; OpenColetorTemplate(coletor); SaveAs2d(coletor); // Salva o 3D e troca referencia no novo 2d SaveAs3d(coletor); InserirPropriedade(coletor); // Replace ramal do rack ReplaceBolsaRack(coletor); // Replace ramal compressor. ReplaceBolsaCP(coletor); SaveAsTubo(coletor); // Salva o 2D final swApp.ActivateDoc(coletor.CodigoColetor + ".SLDDRW"); swModel = swApp.ActiveDoc; int error = 0; int warnings = 0; swModel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_SaveReferenced + (int)swSaveAsOptions_e.swSaveAsOptions_Silent, ref error, ref warnings); swModel.SaveAs(Path.ChangeExtension(swModel.GetPathName(), ".PDF")); swApp.CloseAllDocuments(true); } //Replace(swModel); //swModel.EditRebuild3(); //mView.EnableGraphicsUpdate = true; }
private SolidWorksWrapper() { _app = new SldWorks.SldWorks(); }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); int errors = 0; // must suppress cover to balloon hidden features var delay = 300; var assemblyName = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\blob - L2\blob.L2_cover.SLDASM"; var model = (ModelDoc2)swInstance.ActivateDoc3(assemblyName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); Thread.Sleep(delay); // write to blob.L2_cover.txt '0' to the field "Is Dimensioned" var coverConfigPath = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\blob - L2\blob.L2_cover.txt"; var coverConfigLines = System.IO.File.ReadAllLines(coverConfigPath); var index = 0; var stop = false; while (!stop) { var line = coverConfigLines[index]; if (line.Contains("Is Dimensioned 2 Bool") && !line.Contains("IIF")) { stop = true; var newLine = coverConfigLines[index].Replace("1", "0"); coverConfigLines[index] = newLine; } else { ++index; } } System.IO.File.WriteAllLines(coverConfigPath, coverConfigLines); Thread.Sleep(delay); model.ForceRebuild3(false); Thread.Sleep(delay); // switch to drawing var coverDrawingFileName = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\base blob - L1\blob.cover.SLDDRW"; model = (ModelDoc2)swInstance.ActivateDoc3(coverDrawingFileName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); // draw balloons var drawing = (DrawingDoc)model; var boolStatus = drawing.ActivateView("Drawing View1"); boolStatus = model.Extension.SelectByID2("Drawing View1", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); var autoballoonParameters = drawing.CreateAutoBalloonOptions(); autoballoonParameters.Layout = (int)swBalloonLayoutType_e.swDetailingBalloonLayout_Square; autoballoonParameters.ReverseDirection = false; autoballoonParameters.IgnoreMultiple = false; autoballoonParameters.InsertMagneticLine = true; autoballoonParameters.LeaderAttachmentToFaces = true; autoballoonParameters.Style = (int)swBalloonStyle_e.swBS_Box; autoballoonParameters.Size = (int)swBalloonFit_e.swBF_2Chars; autoballoonParameters.UpperTextContent = (int)swBalloonTextContent_e.swBalloonTextItemNumber; autoballoonParameters.Layername = "Format"; autoballoonParameters.ItemNumberStart = 1; autoballoonParameters.ItemNumberIncrement = 1; autoballoonParameters.ItemOrder = (int)swBalloonItemNumbersOrder_e.swBalloonItemNumbers_DoNotChangeItemNumbers; autoballoonParameters.EditBalloons = true; autoballoonParameters.EditBalloonOption = (int)swEditBalloonOption_e.swEditBalloonOption_Resequence; var vNotes = drawing.AutoBalloon5(autoballoonParameters); // Drawing View2 if exists var status = drawing.ActivateView("Drawing View2"); if (status) { boolStatus = model.Extension.SelectByID2("Drawing View2", "DRAWINGVIEW", 0, 0, 0, false, 0, null, 0); drawing.AutoBalloon5(autoballoonParameters); } model.ClearSelection2(true); Thread.Sleep(delay); // switch back to assembly and unsuppress cover model = (ModelDoc2)swInstance.ActivateDoc3(assemblyName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); Thread.Sleep(delay); // write to config coverConfigLines[index] = coverConfigLines[index].Replace("0", "1"); System.IO.File.WriteAllLines(coverConfigPath, coverConfigLines); Thread.Sleep(delay); model.ForceRebuild3(false); Thread.Sleep(delay); model.ForceRebuild3(false); Thread.Sleep(delay); // back to drawing swInstance.ActivateDoc3(coverDrawingFileName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); }
static void Main(string[] args) { var swInstance = new SldWorks.SldWorks(); // read from app data to populate the 3 expected paths // currently: cover assembly, cover assembly config, cover drawing paths var appDataPath = @"C:\Users\bolinger\Documents\SolidWorks Projects\Prefab Blob - Cover Blob\app data\rebuild.txt"; var appDataLines = System.IO.File.ReadAllLines(appDataPath); // make blob.L2_cover.SLDASM the active SW document var coverAssemblyFileName = getFileNameFromPath(appDataLines[0]); var errors = 0; var model = (ModelDoc2)swInstance.ActivateDoc3(coverAssemblyFileName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); // write to blob.L2_cover.txt '0' to the field "Is Dimensioned" var coverConfigPath = appDataLines[1]; var coverConfigLines = System.IO.File.ReadAllLines(coverConfigPath); var index = 0; var stop = false; while (!stop) { var line = coverConfigLines[index]; if (line.Contains("Is Dimensioned") && !line.Contains("IIF")) { stop = true; var newLine = coverConfigLines[index].Replace("1", "0"); coverConfigLines[index] = newLine; } else { ++index; } } System.IO.File.WriteAllLines(coverConfigPath, coverConfigLines); // wait for write var delay = 300; Thread.Sleep(delay); // rebuild to suppress assembly features model.ForceRebuild3(false); // wait a second Thread.Sleep(delay); // make blob.cover.SLDDRW the active SW document var coverDrawingFileName = getFileNameFromPath(appDataLines[2]); model = (ModelDoc2)swInstance.ActivateDoc3(coverDrawingFileName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); // wait a second Thread.Sleep(delay); // draw annotations to drawing doc var drawing = (DrawingDoc)model; var annotations = (object[])drawing.InsertModelAnnotations3( (int)swImportModelItemsSource_e.swImportModelItemsFromEntireModel, (int)swInsertAnnotation_e.swInsertDimensionsMarkedForDrawing, true, false, false, false); // second dimension - hidden doesn't work Thread.Sleep(delay); model = (ModelDoc2)swInstance.ActivateDoc3(coverAssemblyFileName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); var index2 = 0; stop = false; while (!stop) { var line = coverConfigLines[index2]; if (line.Contains("Is Dimensioned 2") && !line.Contains("IIF")) { stop = true; var newLine = coverConfigLines[index2].Replace("1", "0"); coverConfigLines[index2] = newLine; } else { ++index2; } } System.IO.File.WriteAllLines(coverConfigPath, coverConfigLines); Thread.Sleep(delay); model.ForceRebuild3(false); Thread.Sleep(delay); swInstance.ActivateDoc3(coverDrawingFileName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); Thread.Sleep(delay); drawing.InsertModelAnnotations3( (int)swImportModelItemsSource_e.swImportModelItemsFromEntireModel, (int)swInsertAnnotation_e.swInsertDimensionsMarkedForDrawing, true, false, false, false); // wait a second Thread.Sleep(delay); // make blob.L2_cover.SLDASM the active SW document model = (ModelDoc2)swInstance.ActivateDoc3(coverAssemblyFileName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); // write unsuppress to assembly config coverConfigLines[index] = coverConfigLines[index].Replace("0", "1"); coverConfigLines[index2] = coverConfigLines[index2].Replace("0", "1"); System.IO.File.WriteAllLines(coverConfigPath, coverConfigLines); // wait a second Thread.Sleep(delay); // rebuild assembly - necessary to unsuppress drawing model.ForceRebuild3(false); // wait a second Thread.Sleep(delay); // final rebuild model.ForceRebuild3(false); // wait a second Thread.Sleep(delay); // make blob.cover.SLDDRW the active SW document model = (ModelDoc2)swInstance.ActivateDoc3(coverDrawingFileName, true, (int)swRebuildOnActivation_e.swRebuildActiveDoc, ref errors); }
/// <summary> /// 指定のフォルダ内にある3D モデルファイルを一括で別形式に変換するプログラム /// </summary> /// <param name="args"></param> static void Main(string[] args) { if (args.Count() > 0) { foreach (string arg in args) { switch (arg.Substring(0, arg.IndexOf("="))) { case "--tn": string argVal = arg.Substring(arg.IndexOf("=") + 1); if (argVal == "true") { thumbnail = true; } break; default: break; } } } string[] files = System.IO.Directory.GetFiles(directory); foreach (string file in files) { string filename = file.Substring(file.LastIndexOf("\\") + 1, file.IndexOf(".") - file.LastIndexOf("\\") - 1); swApp = new SldWorks.SldWorks(); swApp.Visible = thumbnail; Console.WriteLine(file); bool bRet = false; string strArg = null; int Err = 0; object importData = swApp.GetImportFileData(file); swModel = swApp.LoadFile4(file, strArg, importData, ref Err); if (thumbnail) { swModel.ShowNamedView2("", 7); swModel.ViewZoomtofit2(); swApp.FrameState = 1; Thread.Sleep(1000); Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Graphics g = Graphics.FromImage(bmp); g.CopyFromScreen(new Point(0, 0), new Point(0, 0), bmp.Size); string directory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + @"\bmp"; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } filename = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + @"\bmp\" + filename + ".bmp"; bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp); g.Dispose(); } string newfilename = file.Remove(file.IndexOf(".")) + extension; swModel.ClearSelection2(true); bRet = swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swStepAP, 214); ModelDocExtension swExt = swModel.Extension; bRet = swExt.SaveAs(newfilename, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, 0, null, Err, 0); swApp.ExitApp(); } }