public void CreateCube() { //make sure we have a part open string partTemplate = iSwApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); if ((partTemplate != null) && (partTemplate != "")) { IModelDoc2 modDoc = (IModelDoc2)iSwApp.NewDocument(partTemplate, (int)swDwgPaperSizes_e.swDwgPaperA2size, 0.0, 0.0); modDoc.InsertSketch2(true); modDoc.SketchRectangle(0, 0, 0, .1, .1, .1, false); //Extrude the sketch IFeatureManager featMan = modDoc.FeatureManager; featMan.FeatureExtrusion(true, false, false, (int)swEndConditions_e.swEndCondBlind, (int)swEndConditions_e.swEndCondBlind, 0.1, 0.0, false, false, false, false, 0.0, 0.0, false, false, false, false, true, false, false); } 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."); } }
protected IDisposable NewDocument(swDocumentTypes_e docType) { var useDefTemplates = m_SwApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAlwaysUseDefaultTemplates); try { m_SwApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAlwaysUseDefaultTemplates, true); var defTemplatePath = m_SwApp.GetDocumentTemplate( (int)docType, "", (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 100, 100); if (string.IsNullOrEmpty(defTemplatePath)) { throw new Exception("Default template is not found"); } var model = (IModelDoc2)m_SwApp.NewDocument(defTemplatePath, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 100, 100); if (model != null) { var docWrapper = new DocumentWrapper(m_SwApp, model); m_Disposables.Add(docWrapper); return(docWrapper); } else { throw new NullReferenceException($"Failed to create new document from '{defTemplatePath}'"); } } finally { m_SwApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swAlwaysUseDefaultTemplates, useDefTemplates); } }
/// <summary> /// 根据模板创建文档 /// </summary> /// <param name="sldWorks"><see cref="ISldWorks"/></param> /// <param name="templatePath">模板路径 支持的文件类型为<para>.prtdot</para><para>.asmdot</para><para>.drwdot</para></param> /// <param name="hidden">是否对用户可见 默认为不可见</param> /// <returns><see cref="ModelDoc2"/></returns> public static ModelDoc2 CreateDocument (this ISldWorks sldWorks, string templatePath, bool hidden = true) { if (!File.Exists(templatePath)) { throw new FileNotFoundException(string.Format("未找到此种类型的模板文件")); } var type = SWPath.GetTemFileType(templatePath); try { if (hidden) { sldWorks.DocumentVisible(false, (int)type); } //TODO:设置替换字符串 var doc = (ModelDoc2)sldWorks.NewDocument(templatePath, (int)swDwgPaperSizes_e.swDwgPaperA4size, 1, 1); return(doc); } finally { if (hidden) { sldWorks.DocumentVisible (true, (int) type); } } }
private IPartDoc NewPartDoc(ISldWorks swApp) { Assert.NotNull(swApp); var partTemPath = swApp.GetUserPreferenceStringValue((int) swUserPreferenceStringValue_e.swDefaultTemplatePart)?.Replace("零件", "gb_part"); Assert.IsTrue(File.Exists(partTemPath)); return(swApp.NewDocument(partTemPath, 0, 0, 0) as IPartDoc); }
public void CreateCube() { //make sure we have a part open string partTemplate = iSwApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); IModelDoc2 modDoc = (IModelDoc2)iSwApp.NewDocument(partTemplate, (int)swDwgPaperSizes_e.swDwgPaperA2size, 0.0, 0.0); modDoc.InsertSketch2(true); modDoc.SketchRectangle(0, 0, 0, .1, .1, .1, false); //Extrude the sketch IFeatureManager featMan = modDoc.FeatureManager; featMan.FeatureExtrusion(true, false, false, (int)swEndConditions_e.swEndCondBlind, (int)swEndConditions_e.swEndCondBlind, 0.1, 0.0, false, false, false, false, 0.0, 0.0, false, false, false, false, true, false, false); }
//create value body public void CreateCube() { valueBodyPpage = new ValueBodyPMPage(this); ShowValueBodyPMP(); return; //make sure we have a part open string partTemplate = iSwApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); if ((partTemplate != null) && (partTemplate != "")) { IModelDoc2 modDoc = (IModelDoc2)iSwApp.NewDocument(partTemplate, (int)swDwgPaperSizes_e.swDwgPaperA2size, 0.0, 0.0); } 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."); } }
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."); } } }
public double Build(double width, double height, double length, out int totalModelsBuilt) { m_TotalModelsBuilt++; var templatePath = m_App.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); var part = m_App.NewDocument(templatePath, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 0, 0) as IPartDoc; var box = m_App.IGetModeler().CreateBodyFromBox( new double[] { 0, 0, 0, 1, 0, 0, width, length, height }); var feat = part.CreateFeatureFromBody3(box, false, (int)swCreateFeatureBodyOpts_e.swCreateFeatureBodySimplify); int errs = -1; int warns = -1; var outPath = Path.Combine(m_BuildDir, $"{DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")}.sldprt"); var dir = Path.GetDirectoryName(outPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } (part as IModelDoc2).Extension.SaveAs(outPath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errs, ref warns); totalModelsBuilt = m_TotalModelsBuilt; var mass = (part as IModelDoc2).Extension.CreateMassProperty().Mass; m_App.CloseDoc((part as IModelDoc2).GetTitle()); return(mass); }
public void CreateCube() { IModelDoc2 modDoc = (IModelDoc2)iSwApp.NewDocument("", (int)swDwgPaperSizes_e.swDwgPaperA2size, 0.0, 0.0); modDoc.InsertSketch2(true); modDoc.SketchRectangle(0, 0, 0, .1, .1, .1, false); //Extrude the sketch IFeatureManager featMan = modDoc.FeatureManager; featMan.FeatureExtrusion(true, false, false, (int)swEndConditions_e.swEndCondBlind, (int)swEndConditions_e.swEndCondBlind, 0.1, 0.0, false, false, false, false, 0.0, 0.0, false, false, false, false, true, false, false); }
public static ModelDoc2 CreateHiddenDocument (this ISldWorks sldWorks, bool hidden = true, swDocumentTypes_e type = swDocumentTypes_e.swDocPART) { try { if (hidden) { sldWorks.DocumentVisible(false, (int)type); } var partTemplateName = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); var doc = (ModelDoc2)sldWorks.NewDocument(partTemplateName, (int)swDwgPaperSizes_e.swDwgPaperA4size, 1, 1); doc.Visible = false; /* * ModelView myModelView = null; * myModelView = ((ModelView)(doc.ActiveView)); * myModelView.FrameLeft = 0; * myModelView.FrameTop = 0; * myModelView = ((ModelView)(doc.ActiveView)); * * myModelView.FrameState = ((int)(swWindowState_e.swWindowMinimized)); */ return(doc); } finally { if (hidden) { sldWorks.DocumentVisible (true, (int) type); } } }
public static void Create(ISldWorks app, ModelDoc2 mainModel) { string drawingTemplate = app.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateDrawing); ModelDoc2 designProject = app.NewDocument(drawingTemplate, (int)swDwgPaperSizes_e.swDwgPaperBsize, 0, 0); DrawingDoc designProjectDrawing = (DrawingDoc)designProject; int errors = 0; app.ActivateDoc2(designProject.GetTitle(), false, ref errors); designProjectDrawing.SetupSheet5("", (int)swDwgPaperSizes_e.swDwgPapersUserDefined, (int)swDwgTemplates_e.swDwgTemplateCustom, 1, 100, false, "a4 - iso.slddrt", 0.297, 0.21, "", true); var h = designProjectDrawing.CreateDrawViewFromModelView3(mainModel.GetPathName(), "*Изометрия", 0.1, 0.2, 0); List<OrderComponentData> orderData = new List<OrderComponentData>(); object[] allComponents = ((AssemblyDoc)mainModel).GetComponents(true); foreach (Component2 component in allComponents) { ModelDoc2 currentModel = component.GetModelDoc2(); string ip = GetCustomPropertyValue(currentModel, "IsProduct"); if (ip == "Yes") { orderData.Add( new OrderComponentData() { Article = GetCustomPropertyValue(currentModel, "Articul"), Name = GetCustomPropertyValue(currentModel, "Part_Name_spec"), Width = GetCustomPropertyValue(currentModel, "Size1_spec"), Depth = GetCustomPropertyValue(currentModel, "Size2_spec"), Height = GetCustomPropertyValue(currentModel, "Size3_spec"), Color1 = GetCustomPropertyValue(currentModel, "Color1"), Color2 = GetCustomPropertyValue(currentModel, "Color2"), Color3 = GetCustomPropertyValue(currentModel, "Color3"), Color4 = GetCustomPropertyValue(currentModel, "Color4"), Color5 = GetCustomPropertyValue(currentModel, "Color5"), Color6 = GetCustomPropertyValue(currentModel, "Color6"), Color7 = GetCustomPropertyValue(currentModel, "Color7") }); } } TableAnnotation table = designProjectDrawing.InsertTableAnnotation(0.01, 0.15, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft, orderData.Count + 1, 14); table.BorderLineWeight = 0; table.GridLineWeight = 0; #region Заполнение заголовков колонок таблицы table.set_Text(0, 0, "Поз."); table.set_Text(0, 1, "Артикул"); table.set_Text(0, 2, "Наименование изделия"); table.set_Text(0, 3, "Ширина"); table.set_Text(0, 4, "Глубина"); table.set_Text(0, 5, "Высота"); table.set_Text(0, 6, "Цвет 1"); table.set_Text(0, 7, "Цвет 2"); table.set_Text(0, 8, "Цвет 3"); table.set_Text(0, 9, "Цвет 4"); table.set_Text(0, 10, "Цвет 5"); table.set_Text(0, 11, "Цвет 6"); table.set_Text(0, 12, "Цвет 7"); table.set_Text(0, 13, "Кол-во"); #endregion int i = 1; foreach (OrderComponentData productData in orderData) { table.set_Text(i, 0, i.ToString()); table.set_Text(i, 1, productData.Article); table.set_Text(i, 2, productData.Name); table.set_Text(i, 3, productData.Width); table.set_Text(i, 4, productData.Depth); table.set_Text(i, 5, productData.Height); table.set_Text(i, 6, productData.Color1); table.set_Text(i, 7, productData.Color2); table.set_Text(i, 8, productData.Color3); table.set_Text(i, 9, productData.Color4); table.set_Text(i, 10, productData.Color5); table.set_Text(i, 11, productData.Color6); table.set_Text(i, 12, productData.Color7); i++; } table.SetColumnWidth(0, 0.013, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); table.SetColumnWidth(1, 0.025, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); table.SetColumnWidth(2, 0.07, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); for (int j = 3; j < 14; j++) { table.SetColumnWidth(j, 0.02, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); } designProject.ViewZoomtofit2(); }
/// <summary> /// 后台创建文档 /// </summary> /// <param name="sldWorks"></param> /// <param name="hidden"></param> /// <param name="type"></param> /// <returns></returns> public static ModelDoc2 CreateDocument (this ISldWorks sldWorks, bool hidden = true, swDocumentTypes_e type = swDocumentTypes_e.swDocPART) { try { if (hidden) { sldWorks.DocumentVisible(false, (int)type); } string templatePath = string.Empty; switch (type) { case swDocumentTypes_e.swDocPART: templatePath = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); break; case swDocumentTypes_e.swDocASSEMBLY: templatePath = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateAssembly); break; case swDocumentTypes_e.swDocDRAWING: templatePath = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateDrawing); break; default: break; } if (string.IsNullOrEmpty(templatePath)) { throw new FileNotFoundException(string.Format("未找到此种类型的模板文件:{0}", type.ToString())); } if (!File.Exists(templatePath)) { templatePath = Path.GetDirectoryName(templatePath) + "\\" + Path.GetFileName(templatePath). Replace("零件", "gb_part"). Replace("装配体", "gb_assembly").Replace("工程图", "gb_a1"); } if (!File.Exists(templatePath)) { throw new FileNotFoundException("无法找到SolidWorks文件--" + templatePath); } //TODO:设置替换字符串 var doc = (ModelDoc2)sldWorks.NewDocument(templatePath, (int)swDwgPaperSizes_e.swDwgPaperA4size, 1, 1); if (hidden) { doc.Visible = false; sldWorks.DocumentVisible(false, (int)type); } /* * ModelView myModelView = null; * myModelView = ((ModelView)(doc.ActiveView)); * myModelView.FrameLeft = 0; * myModelView.FrameTop = 0; * myModelView = ((ModelView)(doc.ActiveView)); * * myModelView.FrameState = ((int)(swWindowState_e.swWindowMinimized)); */ return(doc); } finally { if (hidden) { sldWorks.DocumentVisible (true, (int) type); } } }
private void buttonAuto_Click(object sender, EventArgs e) { //新建一个零件 ,画一条150长度的直线,然后最大化. ISldWorks iswApp = Utility.ConnectToSolidWorks(); string partDefaultPath = iswApp.GetDocumentTemplate(1, "", 0, 0, 0); var part = iswApp.NewDocument(partDefaultPath, 0, 0, 0); ModelDoc2 modelDoc = (ModelDoc2)iswApp.ActiveDoc; modelDoc.Extension.SelectByID2("Plane1", "PLANE", 0, 0, 0, false, 0, null, 0); modelDoc.SketchManager.InsertSketch(true); modelDoc.SketchManager.CreateLine(0, 0.1, 0, 0, 0, 0); modelDoc.SketchManager.InsertSketch(true); modelDoc.ClearSelection2(true); modelDoc.Extension.SelectByID2("Sketch1", "SKETCH", 0, 0, 0, false, 1, null, 0); var b = modelDoc.InsertCompositeCurve(); modelDoc.ClearSelection2(true); modelDoc.FeatureManager.ViewFeatures = false; modelDoc.ViewZoomtofit2(); ModelView modelView = (ModelView)modelDoc.ActiveView; iswApp.FrameState = 1; //最大化solidworks modelDoc.ViewZoomtofit2(); modelView.Scale2 = 0.5; // modelDoc.ClearSelection2(true); string ImagePath = @"D:\temp.JPG"; modelDoc.SaveAs3(ImagePath, 0, 0); int LineInImage = img2color(ImagePath); try { System.IO.File.Delete(ImagePath); } catch (Exception exception) { Console.WriteLine(exception); } if (LineInImage > 0) { double ActionScreenHeight = double.Parse(txtSCHeight.Text); //GetScreenRealWeight(double.Parse( textScreenSize.Text)); //当前视图的比例 double ActionScale = modelView.Scale2; //solidworks中的直线占比 double defaultSolidworksP = LineInImage / 1200.0;//double.Parse(txtScreenY.Text); //当前比例下 1像素 等于多少mm double thisSc = 100 / LineInImage; //实际屏幕 1 像素尺寸 double oneP = (ActionScreenHeight) / 1200.0; //当比例设置为 1时 1像素能表示的长度: double onePshowLength = thisSc / ActionScale; //959 1370 GetWindowsSize getWindowSize = new GetWindowsSize(); GetWindowsSize.windsize solidworksize = getWindowSize.GetSize("SLDWORKS"); double getSC = 50.0 / (LineInImage * oneP); txtSC.Text = getSC.ToString();// getSC.ToString(); modelView.Scale2 = getSC; modelDoc.GraphicsRedraw2(); Debug.Print(getSC.ToString()); // modelView.Scale2 = double.Parse(txtSC.Text); // sldWorks.scen } iswApp.CloseDoc(modelDoc.GetPathName()); }
public void Create3DPCB() { if (Directory.Exists("D:\\PDM\\")) { pdm_path = "D:\\PDM\\"; } else if (Directory.Exists("C:\\PDM\\")) { pdm_path = "C:\\PDM\\"; } else { MessageBox.Show("Не найден путь PDM"); return; } //iSwApp.CommandInProgress = true; Board board; string filename; filename = iSwApp.GetOpenFileName("Открыть файл", "", "xml Files (*.xml)|*.xml|", out _, out _, out _); //Board.GetFilename(); if (string.IsNullOrWhiteSpace(filename)) { return; } board = Board.GetfromXML(filename); if (board == null) { MessageBox.Show("XML с неверной структурой", "Ошибка чтения файла"); return; } ModelDoc2 swModel; AssemblyDoc swAssy; ModelView activeModelView; iSwApp.UnloadAddIn(sAddinName); //Новая сборка платы double swSheetWidth = 0, swSheetHeight = 0; string boardName; int Errors = 0, Warnings = 0; swAssy = (AssemblyDoc)iSwApp.NewDocument(pdm_path + "EPDM_LIBRARY\\EPDM_SolidWorks\\EPDM_SWR_Templates\\Модуль_печатной_платы.asmdot", (int)swDwgPaperSizes_e.swDwgPaperA2size, swSheetWidth, swSheetHeight); swModel = (ModelDoc2)swAssy; //Сохранение boardName = filename.Remove(filename.Length - 3) + "SLDASM"; swModel.Extension.SaveAs(boardName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_UpdateInactiveViews, null, ref Errors, ref Warnings); //********** //Доска Component2 board_body; PartDoc part; ModelDoc2 swCompModel; Feature swRefPlaneFeat, plane; swAssy.InsertNewVirtualPart(null, out board_body); board_body.Select4(false, null, false); swAssy.EditPart(); swCompModel = (ModelDoc2)board_body.GetModelDoc2(); part = (PartDoc)swCompModel; part.SetMaterialPropertyName2("-00", "гост материалы.sldmat", "Rogers 4003C"); int j = 1; do { swRefPlaneFeat = (Feature)swCompModel.FeatureByPositionReverse(j); j++; }while (swRefPlaneFeat.Name != "Спереди"); plane = (Feature)board_body.GetCorresponding(swRefPlaneFeat); plane.Select2(false, -1); swModel.SketchManager.InsertSketch(false); swModel.SketchManager.AddToDB = true; //Эскизы swModel.SketchManager.DisplayWhenAdded = false; //Контур foreach (object skt in board.sketh) { if (skt.GetType().FullName == "SWAddin.Line") { Line sk = (Line)skt; swModel.SketchManager.CreateLine(sk.x1, sk.y1, 0, sk.x2, sk.y2, 0); } if (skt.GetType().FullName == "SWAddin.Arc") { Arc sk = (Arc)skt; swModel.SketchManager.CreateArc(sk.xc, sk.yc, 0, sk.x1, sk.y1, 0, sk.x2, sk.y2, 0, sk.direction); } } swModel.FeatureManager.FeatureExtrusion3(true, false, false, 0, 0, board.thickness, board.thickness, false, false, false, false, 0, 0, false, false, false, false, true, true, true, 0, 0, false); swModel.ClearSelection2(true); //Вырезы if (board.cutout.Count > 2) { plane.Select2(false, -1); swModel.SketchManager.InsertSketch(false); swModel.SketchManager.AddToDB = true; foreach (object skt in board.cutout) { if (skt.GetType().FullName == "SWAddin.Line") { Line sk = (Line)skt; swModel.SketchManager.CreateLine(sk.x1, sk.y1, 0, sk.x2, sk.y2, 0); } if (skt.GetType().FullName == "SWAddin.Arc") { Arc sk = (Arc)skt; swModel.SketchManager.CreateArc(sk.xc, sk.yc, 0, sk.x1, sk.y1, 0, sk.x2, sk.y2, 0, sk.direction); } } swModel.FeatureManager.FeatureCut4(true, false, true, 1, 0, board.thickness, board.thickness, false, false, false, false, 1.74532925199433E-02, 1.74532925199433E-02, false, false, false, false, false, true, true, true, true, false, 0, 0, false, false); } //Отверстия if (board.circles.Count > 0) { List <Circle> items; items = board.circles.FindAll(hole => hole.radius.CompareTo(0.001) > 0); if (items.Count > 0) { plane.Select2(false, -1); swModel.SketchManager.InsertSketch(false); swModel.SketchManager.AddToDB = true; foreach (Circle c in items) { swModel.SketchManager.CreateCircleByRadius(c.xc, c.yc, 0, c.radius); } swModel.FeatureManager.FeatureCut4(true, false, true, 1, 0, board.thickness, board.thickness, false, false, false, false, 1.74532925199433E-02, 1.74532925199433E-02, false, false, false, false, false, true, true, true, true, false, 0, 0, false, false); } items = board.circles.FindAll(hole => hole.radius.CompareTo(0.001) <= 0); if (items.Count > 0) { plane.Select2(false, -1); swModel.SketchManager.InsertSketch(false); swModel.SketchManager.AddToDB = true; foreach (Circle c in items) { swModel.SketchManager.CreateCircleByRadius(c.xc, c.yc, 0, c.radius); } swModel.FeatureManager.FeatureCut4(true, false, true, 1, 0, board.thickness, board.thickness, false, false, false, false, 1.74532925199433E-02, 1.74532925199433E-02, false, false, false, false, false, true, true, true, true, false, 0, 0, false, false); } } //swModel.FeatureManager.FeatureCut3(true, false, true, 1, 0, board.thickness, board.thickness, false, false, false, false, 1.74532925199433E-02, 1.74532925199433E-02, false, false, false, false, false, true, true, true, true, false, 0, 0, false); swModel.SketchManager.DisplayWhenAdded = true; swModel.SketchManager.AddToDB = false; swAssy.HideComponent(); swAssy.ShowComponent(); swModel.ClearSelection2(true); swAssy.EditAssembly(); string path, sample; switch (board.ver) { case 1: path = pdm_path + "Прочие изделия\\ЭРИ"; break; case 2: path = pdm_path + "Прочие изделия\\Footprint"; break; default: path = pdm_path + "Прочие изделия\\ЭРИ"; break; } List <string> allFoundFiles = new List <string>(Directory.GetFiles(path, "*.SLD*", SearchOption.AllDirectories)); allFoundFiles.AddRange(Directory.GetFiles(pdm_path + "Прочие изделия\\ЭРИ\\T", "*.SLD*", SearchOption.AllDirectories)); List <string> allFind; Dictionary <string, string> empty = new Dictionary <string, string>(); Dictionary <string, string> hollow = new Dictionary <string, string>(); Dictionary <string, string> multiple = new Dictionary <string, string>(); foreach (Component comp in board.components) { //Выбор по какому полю искать 3Д модель //sample = comp.part_Number; sample = comp.title.Replace((char)47, (char)95); sample = sample.Replace((char)92, (char)95); if (board.ver == 2) { sample = comp.footprint.Replace((char)47, (char)95); sample = sample.Replace((char)92, (char)95); if ((sample.EndsWith("N") & !sample.EndsWith("DN")) | (sample.EndsWith("M") & !sample.EndsWith("DM")) | (sample.EndsWith("L") & !sample.EndsWith("DL"))) { sample = sample.Remove(sample.Length - 1); } if (sample.EndsWith("DN") | sample.EndsWith("DM") | sample.EndsWith("DL")) { sample = sample.Remove(sample.Length - 2); } } //Ищем пустые футпринты if (string.IsNullOrEmpty(sample)) { if (!hollow.ContainsKey(comp.title)) { hollow.Add(comp.title, comp.title); } } //Ищем повторы allFind = allFoundFiles.FindAll(item => item.IndexOf(sample, StringComparison.OrdinalIgnoreCase) != -1); if (allFind.Count > 1) { if (!multiple.ContainsKey(comp.title)) { multiple.Add(comp.title, comp.footprint); } } //Регистронезависимый поиск comp.fileName = allFoundFiles.Find(item => item.IndexOf(sample, StringComparison.OrdinalIgnoreCase) != -1); //comp.fileName = allFoundFiles.Find(item => item.Contains(sample)); if (string.IsNullOrWhiteSpace(comp.fileName) & (board.ver != 2)) { sample = comp.part_Number.Replace((char)47, (char)95); sample = sample.Replace((char)92, (char)95); comp.fileName = allFoundFiles.Find(item => item.IndexOf(sample, StringComparison.OrdinalIgnoreCase) != -1); } if (string.IsNullOrWhiteSpace(comp.fileName)) { comp.fileName = pdm_path + "Прочие изделия\\ЭРИ\\Zero.SLDPRT"; if (!empty.ContainsKey(sample)) { empty.Add(sample, sample); } } } double[] transforms, dMatrix; string[] coordSys, names; double alfa, beta, gamma, x, y, z; names = new string[board.components.Count]; coordSys = new string[board.components.Count]; dMatrix = new double[16]; transforms = new double[board.components.Count * 16]; for (int i = 0; i < board.components.Count; i++) { names[i] = board.components[i].fileName; } int n = 0; foreach (Component comp in board.components) { alfa = 0; x = comp.x; y = comp.y; //z = comp.z; if (comp.layer == 1) //Если Top { //z = (comp.z + comp.standOff) standOff не учитывается z = board.thickness; beta = -Math.PI / 2; } else //Иначе Bottom { // z = (comp.z - comp.standOff) standOff не учитывается z = 0; beta = Math.PI / 2; } gamma = -(comp.rotation / 180) * Math.PI; dMatrix[0] = Math.Cos(alfa) * Math.Cos(gamma) - Math.Sin(alfa) * Math.Cos(beta) * Math.Sin(gamma); dMatrix[1] = -Math.Cos(alfa) * Math.Sin(gamma) - Math.Sin(alfa) * Math.Cos(beta) * Math.Cos(gamma); dMatrix[2] = Math.Sin(alfa) * Math.Sin(beta); //1 строка матрицы вращения dMatrix[3] = Math.Sin(alfa) * Math.Cos(gamma) + Math.Cos(alfa) * Math.Cos(beta) * Math.Sin(gamma); dMatrix[4] = -Math.Sin(alfa) * Math.Sin(gamma) + Math.Cos(alfa) * Math.Cos(beta) * Math.Cos(gamma); dMatrix[5] = -Math.Cos(alfa) * Math.Sin(beta); //2 строка матрицы вращения dMatrix[6] = Math.Sin(beta) * Math.Sin(gamma); dMatrix[7] = Math.Sin(beta) * Math.Cos(gamma); dMatrix[8] = Math.Cos(beta); //3 строка матрицы вращения dMatrix[9] = x; dMatrix[10] = y; dMatrix[11] = z; //Координаты dMatrix[12] = 1; //Масштаб dMatrix[13] = 0; dMatrix[14] = 0; dMatrix[15] = 0; //Ничего for (int k = 0; k < dMatrix.Length; k++) { transforms[n * 16 + k] = dMatrix[k]; } n++; } //Вставка swAssy.AddComponents3(names, transforms, coordSys); //Фиксация swModel.Extension.SelectAll(); swAssy.FixComponent(); swModel.ClearSelection2(true); activeModelView = (ModelView)swModel.ActiveView; activeModelView.DisplayMode = (int)swViewDisplayMode_e.swViewDisplayMode_ShadedWithEdges; //**************************** UserProgressBar pb; iSwApp.GetUserProgressBar(out pb); //Заполнение поз. обозначений List <Component2> compsColl = new List <Component2>(); //Коллекция из компонентов сборки платы Feature swFeat; Component2 compTemp; pb.Start(0, board.components.Count, "Поиск"); int itm = 0; swFeat = (Feature)swModel.FirstFeature(); while (swFeat != null) { pb.UpdateProgress(itm); //pb.UpdateTitle(itm); if (swFeat.GetTypeName().Equals("Reference")) //Заполняем коллекцию изделиями { compTemp = (Component2)swFeat.GetSpecificFeature2(); compsColl.Add(compTemp); } swFeat = (Feature)swFeat.GetNextFeature(); itm++; } pb.End(); compsColl[0].Name2 = board.designator + (char)32 + "Плата печатная"; //Пререименовываем деталь if (compsColl.Count - 1 == board.components.Count) //Проверка чтобы не сбились поз. обозначения, если появятся значит все правильно иначе они не нужны { for (int i = 0; i < board.components.Count; i++) { compsColl[i + 1].ComponentReference = board.components[i].physicalDesignator; //Заполняем поз. обозначениями } } string estr = ""; iSwApp.LoadAddIn(sAddinName); if (empty.Count != 0 | hollow.Count != 0 | multiple.Count != 0) { if (empty.Count != 0) { estr = "Отсутствуют 3d модели футпринтов" + System.Environment.NewLine; StreamWriter writer = new StreamWriter(filename.Remove(filename.Length - 4) + "_footprint" + ".txt", false); foreach (KeyValuePair <string, string> str in empty) { estr = estr + str.Key + System.Environment.NewLine; writer.WriteLine(str.Value); } writer.Close(); } if (hollow.Count != 0) { estr = estr + "У этих компонентов пустые строки футпринтов" + System.Environment.NewLine; foreach (KeyValuePair <string, string> str in hollow) { estr = estr + str.Key + System.Environment.NewLine; } } if (multiple.Count != 0) { estr = estr + "Найдено несколько футпринтов этих компонентов" + System.Environment.NewLine; StreamWriter writer_m = new StreamWriter(filename.Remove(filename.Length - 4) + "_дубляжи" + ".txt", false); foreach (KeyValuePair <string, string> str in multiple) { estr = estr + str.Key + "->" + str.Value + System.Environment.NewLine; writer_m.WriteLine(str.Key + "->" + str.Value); } writer_m.Close(); } MessageBox.Show(estr, "Внимание"); //swApp.SendMsgToUser2("Не найдены" + estr, 2, 2); } //iSwApp.CommandInProgress = false; //************** }
/// <summary> /// /// </summary> /// <param name="assemblyName"></param> /// <param name="partsname"></param> private void CreateNewAssembly(string assemblyName, List <string> partsname) { string assemblyDefaultPath = iswApp.GetDocumentTemplate(2, "", 0, 0, 0); var part = iswApp.NewDocument(assemblyDefaultPath, 0, 0, 0); if (part != null) { AssemblyDoc assemblyDoc = part as AssemblyDoc; ModelDoc2 modelDoc2 = assemblyDoc as ModelDoc2; ModelDocExtension swModExt = default(ModelDocExtension); int errors = 0; int warnings = 0; swModExt = (ModelDocExtension)modelDoc2.Extension; swModExt.SaveAs(assemblyName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, errors, warnings); modelDoc2 = (ModelDoc2)iswApp.ActiveDoc; int i = 0; int tempV = ProgressBar.Value; foreach (var partN in partsname) { labStatus.Text = "正在装配-->" + Path.GetFileNameWithoutExtension(partN); ProgressBar.Value = tempV + i; iswApp.OpenDoc6(partN.ToString(), 1, 32, "", ref errors, ref warnings); assemblyDoc = (AssemblyDoc)iswApp.ActivateDoc3(System.IO.Path.GetFileNameWithoutExtension(assemblyName) + ".sldasm", true, 0, errors); Component2 swInsertedComponent = default(Component2); swInsertedComponent = assemblyDoc.AddComponent5(partN, 0, "", false, "", 0, 0, 0); modelDoc2 = (ModelDoc2)iswApp.ActiveDoc; modelDoc2.ClearSelection2(true); modelDoc2.Extension.SelectByID2(swInsertedComponent.GetSelectByIDString(), "COMPONENT", 0, 0, 0, false, 0, null, 0); assemblyDoc.UnfixComponent(); modelDoc2.ClearSelection2(true); modelDoc2.Extension.SelectByID2("Point1@Origin@" + swInsertedComponent.GetSelectByIDString(), "EXTSKETCHPOINT", 0, 0, 0, false, 0, null, 0); modelDoc2.Extension.SelectByID2("Point1@Origin", "EXTSKETCHPOINT", 0, 0, 0, true, 0, null, 0); Mate2 mate2 = default(Mate2); mate2 = assemblyDoc.AddMate5(20, -1, false, 0, 0, 0, 0, 0.001, 0, 0, 0, false, false, 0, out int warings); modelDoc2.ClearSelection2(true); modelDoc2.EditRebuild3(); iswApp.CloseDoc(partN); i = i + 1; } iswApp.ActivateDoc3(System.IO.Path.GetFileNameWithoutExtension(assemblyName) + ".sldasm", true, 0, errors); modelDoc2 = (ModelDoc2)iswApp.ActiveDoc; modelDoc2.ShowNamedView2("*等轴测", 7); modelDoc2.ViewZoomtofit2(); modelDoc2.Save(); } ProgressBar.Value = ProgressBar.Maximum; }
public void Create3D() { Board board; string filename; ////SolidWorks //Console.WriteLine("Подключение к SldWorks.Application"); //var progId = "SldWorks.Application.27"; //var progType = System.Type.GetTypeFromProgID(progId); //var swApp = System.Activator.CreateInstance(progType) as ISldWorks; //swApp.Visible = true; //Console.WriteLine("Успешное подключение к версии SldWorks.Application " + swApp.RevisionNumber()); //Console.WriteLine(DateTime.Now.ToString()); //Console.CursorSize = 100; filename = iSwApp.GetOpenFileName("Открыть файл", "", "xml Files (*.xml)|*.xml|", out _, out _, out _); //Board.GetFilename(); if (String.IsNullOrWhiteSpace(filename)) { return; } //System.Environment.Exit(0); board = Board.GetfromXML(filename); ModelDoc2 swModel; AssemblyDoc swAssy; ModelView activeModelView; //Новая сборка платы double swSheetWidth = 0, swSheetHeight = 0; string boardName; int Errors = 0, Warnings = 0; swAssy = (AssemblyDoc)iSwApp.NewDocument("D:\\PDM\\EPDM_LIBRARY\\EPDM_SolidWorks\\EPDM_SWR_Templates\\Модуль_печатной_платы.asmdot", (int)swDwgPaperSizes_e.swDwgPaperA2size, swSheetWidth, swSheetHeight); swModel = (ModelDoc2)swAssy; //Сохранение boardName = filename.Remove(filename.Length - 3) + "SLDASM"; Console.WriteLine(boardName); swModel.Extension.SaveAs(boardName, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_UpdateInactiveViews, null, ref Errors, ref Warnings); //********** //Доска Component2 board_body; PartDoc part; ModelDoc2 swCompModel; Feature swRefPlaneFeat, plane; swAssy.InsertNewVirtualPart(null, out board_body); board_body.Select4(false, null, false); swAssy.EditPart(); swCompModel = (ModelDoc2)board_body.GetModelDoc2(); part = (PartDoc)swCompModel; part.SetMaterialPropertyName2("-00", "гост материалы.sldmat", "Rogers 4003C"); int j = 1; do { swRefPlaneFeat = (Feature)swCompModel.FeatureByPositionReverse(j); j = j + 1; }while (swRefPlaneFeat.Name != "Спереди"); plane = (Feature)board_body.GetCorresponding(swRefPlaneFeat); plane.Select2(false, -1); swModel.SketchManager.InsertSketch(false); swModel.SketchManager.AddToDB = true; //Эскизы foreach (Object skt in board.sketh) { if (skt.GetType().FullName == "ASM_3D.Line") { Line sk = (Line)skt; swModel.SketchManager.CreateLine(sk.x1, sk.y1, 0, sk.x2, sk.y2, 0); } if (skt.GetType().FullName == "ASM_3D.Arc") { Arc sk = (Arc)skt; swModel.SketchManager.CreateArc(sk.xc, sk.yc, 0, sk.x1, sk.y1, 0, sk.x2, sk.y2, 0, sk.direction); } } swModel.FeatureManager.FeatureExtrusion3(true, false, false, 0, 0, board.thickness, board.thickness, false, false, false, false, 0, 0, false, false, false, false, true, true, true, 0, 0, false); swModel.ClearSelection2(true); plane.Select2(false, -1); swModel.SketchManager.InsertSketch(false); swModel.SketchManager.AddToDB = true; swModel.SketchManager.DisplayWhenAdded = false; foreach (Circle c in board.circles) { swModel.SketchManager.CreateCircleByRadius(c.xc, c.yc, 0, c.radius); } swModel.FeatureManager.FeatureCut3(true, false, true, 1, 0, board.thickness, board.thickness, false, false, false, false, 1.74532925199433E-02, 1.74532925199433E-02, false, false, false, false, false, true, true, true, true, false, 0, 0, false); swAssy.HideComponent(); swAssy.ShowComponent(); swModel.ClearSelection2(true); swAssy.EditAssembly(); List <string> allFoundFiles = new List <string>(System.IO.Directory.GetFiles("D:\\PDM\\Прочие изделия\\ЭРИ", "*.*", SearchOption.AllDirectories)); Dictionary <string, string> empty = new Dictionary <string, string>(); foreach (ASM_3D.Component comp in board.components) { comp.fileName = allFoundFiles.Find(item => item.Contains(comp.part_Number)); if (String.IsNullOrWhiteSpace(comp.fileName)) { comp.fileName = "D:\\PDM\\Прочие изделия\\ЭРИ\\Zero.SLDPRT"; if (!empty.ContainsKey(comp.part_Number)) { empty.Add(comp.part_Number, comp.part_Number); } } } double[] transforms, dMatrix; string[] coordSys, names; double alfa, beta, gamma, x, y, z; names = new string[board.components.Count]; coordSys = new string[board.components.Count]; dMatrix = new double[16]; transforms = new double[board.components.Count * 16]; for (int i = 0; i < board.components.Count; i++) { names[i] = board.components[i].fileName; } int n = 0; foreach (ASM_3D.Component comp in board.components) { alfa = 0; x = comp.x; y = comp.y; if (comp.layer == 1) //Если Top { z = (comp.z + comp.standOff); beta = -Math.PI / 2; } else //Иначе Bottom { z = (comp.z - comp.standOff) / 1000; beta = Math.PI / 2; } gamma = -(comp.rotation / 180) * Math.PI; dMatrix[0] = Math.Cos(alfa) * Math.Cos(gamma) - Math.Sin(alfa) * Math.Cos(beta) * Math.Sin(gamma); dMatrix[1] = -Math.Cos(alfa) * Math.Sin(gamma) - Math.Sin(alfa) * Math.Cos(beta) * Math.Cos(gamma); dMatrix[2] = Math.Sin(alfa) * Math.Sin(beta); //1 строка матрицы вращения dMatrix[3] = Math.Sin(alfa) * Math.Cos(gamma) + Math.Cos(alfa) * Math.Cos(beta) * Math.Sin(gamma); dMatrix[4] = -Math.Sin(alfa) * Math.Sin(gamma) + Math.Cos(alfa) * Math.Cos(beta) * Math.Cos(gamma); dMatrix[5] = -Math.Cos(alfa) * Math.Sin(beta); //2 строка матрицы вращения dMatrix[6] = Math.Sin(beta) * Math.Sin(gamma); dMatrix[7] = Math.Sin(beta) * Math.Cos(gamma); dMatrix[8] = Math.Cos(beta); //3 строка матрицы вращения dMatrix[9] = x; dMatrix[10] = y; dMatrix[11] = z; //Координаты dMatrix[12] = 1; //Масштаб dMatrix[13] = 0; dMatrix[14] = 0; dMatrix[15] = 0; //Ничего for (int k = 0; k < dMatrix.Length; k++) { transforms[n * 16 + k] = dMatrix[k]; } n++; } //Вставка swAssy.AddComponents3(names, transforms, coordSys); //Фиксация swModel.Extension.SelectAll(); swAssy.FixComponent(); swModel.ClearSelection2(true); activeModelView = (ModelView)swModel.ActiveView; activeModelView.DisplayMode = (int)swViewDisplayMode_e.swViewDisplayMode_ShadedWithEdges; //**************************** UserProgressBar pb; iSwApp.GetUserProgressBar(out pb); //Заполнение поз. обозначений List <Component2> compsColl = new List <Component2>(); //Коллекция из компонентов сборки платы Feature swFeat; Component2 compTemp; pb.Start(0, board.components.Count, "Поиск"); int itm = 0; swFeat = (Feature)swModel.FirstFeature(); while (swFeat != null) { pb.UpdateProgress(itm); //pb.UpdateTitle(itm); if (swFeat.GetTypeName().Equals("Reference")) //Заполняем коллекцию изделиями { compTemp = (Component2)swFeat.GetSpecificFeature2(); compsColl.Add(compTemp); } swFeat = (Feature)swFeat.GetNextFeature(); itm++; } pb.End(); compsColl[0].Name2 = "Плата"; //Пререименовываем деталь if (compsColl.Count - 1 == board.components.Count) //Проверка чтобы не сбились поз. обозначения, если появятся значит все правильно иначе они не нужны { for (int i = 0; i < board.components.Count; i++) { compsColl[i + 1].ComponentReference = board.components[i].physicalDesignator; //Заполняем поз. обозначениями } } string estr = ""; if (empty.Count != 0) { foreach (KeyValuePair <string, string> str in empty) { estr = estr + str.Value + System.Environment.NewLine; } MessageBox.Show(estr, "Не найдены"); //swApp.SendMsgToUser2("Не найдены" + estr, 2, 2); } //************** //swApp.ExitApp(); //swApp = null; }