public void OpenDrawing() { ModelDoc2 swModel = iSwApp.ActiveDoc; //SelectionMgr selMgr = new SelectionMgr(); int iErrors = 0; int iWarnings = 0; Component2 swComponent; String swComponentPath; SelectionMgr selMgr = default(SelectionMgr); selMgr = (SelectionMgr)swModel.SelectionManager; swComponent = selMgr.GetSelectedObjectsComponent4(1, -1); try { swComponentPath = swComponent.GetPathName(); } catch (NullReferenceException) { swComponentPath = swModel.GetPathName(); //swComponentPath = swComponent.GetPathName(); } var swDrawingArr = swComponentPath.Split('.'); String swDrawPath = swDrawingArr[0] + ".SLDDRW"; iSwApp.OpenDoc6(swDrawPath, 3, 1, "", iErrors, iWarnings); //MessageBox.Show(swComponentPath.ToString()); }
/// <summary> /// 得到Sketch中的圆弧和圆 /// </summary> /// <param name="swApp"></param> /// <param name="sketch">草图</param> /// <returns></returns> public static List <SketchArc> GetSegmentArc(this Sketch sketch, SldWorks swApp) { ModelDoc2 swDoc = (ModelDoc2)swApp.ActiveDoc; SelectionMgr swSelMgr = (SelectionMgr)swDoc.SelectionManager; List <SketchArc> segments = new List <SketchArc>(); EnumSketchSegments enumSegments = sketch.IEnumSketchSegments(); if (enumSegments != null) { SketchSegment segment; int next = 1; enumSegments.Next(1, out segment, ref next); while (segment != null) { if (segment.GetType() == (int)swSketchSegments_e.swSketchARC) { segments.Add((SketchArc)segment); } segment = null; enumSegments.Next(1, out segment, ref next); } } return(segments); }
public void TestSelectComponentsList(string modelName) { ModelDoc2 doc = OpenSWDocument(modelName); AssemblyDoc assyDoc = (AssemblyDoc)doc; LinkNode baseNode = Serialization.LoadBaseNodeFromModel(SwApp, doc, out bool abortProcess); Assert.False(abortProcess); Link baseLink = baseNode.GetLink(); List <Component2> componentsToSelect = baseLink.SWComponents; HashSet <string> componentsToSelectNames = new HashSet <string>(componentsToSelect.Select(component => component.Name2)); Common.SelectComponents(doc, componentsToSelect, true); SelectionMgr selManager = doc.SelectionManager; // -1 is the Mark, set to negative one if it's not being used. int numSelected = selManager.GetSelectedObjectCount2(-1); Assert.Equal(componentsToSelect.Count, numSelected); for (int i = 0; i < selManager.GetSelectedObjectCount2(-1); i++) { // -1 is the Mark, set to negative one if it's not being used. Component2 comp = selManager.GetSelectedObjectsComponent4(i, -1); Assert.Contains(comp.Name2, componentsToSelectNames); } SwApp.CloseAllDocuments(true); }
//TODO: CmdSet_Click private void CmdSet_Click(object sender, EventArgs e) { swSelMgr = swModel.SelectionManager; if (swSelMgr.GetSelectedObjectCount() == 1) // Проверка выделения { if (swSelMgr.GetSelectedObjectType(1) == 15) { if (m2 == 1) { VBMath.Randomize(); oldNoteName = "NN" + Strings.LTrim(Convert.ToString(VBMath.Rnd() * 100)); //Debug.Print(oldNoteName); ok = swNote.SetName(oldNoteName); } swNote = swSelMgr.GetSelectedObject2(1); ok = swNote.SetName(newNoteName); Start(); } else { MessageBox.Show("Необходимо выделить заметку"); } } else { MessageBox.Show("Выделите одну заметку..."); } }
/// <summary> /// Run this function after this.Document is populated. It fills two ref vars with swDocumentTypes_e. /// </summary> /// <param name="d">The document type.</param> /// <param name="od">The top-level document type.</param> private void GetTypes(ref swDocumentTypes_e d, ref swDocumentTypes_e od) { swDocumentTypes_e docT = (swDocumentTypes_e)Document.GetType(); ModelDoc2 overDoc = (ModelDoc2)_swApp.ActiveDoc; swDocumentTypes_e overDocT = (swDocumentTypes_e)overDoc.GetType(); if ((docT != swDocumentTypes_e.swDocDRAWING && swSelMgr != null) && swSelMgr.GetSelectedObjectCount2(-1) > 0) { Component2 comp = (Component2)swSelMgr.GetSelectedObjectsComponent4(1, -1); if (comp != null) { ModelDoc2 cmd = (ModelDoc2)comp.GetModelDoc2(); docT = (swDocumentTypes_e)cmd.GetType(); prop.GetPropertyData(comp); comp = null; } else { prop.GetPropertyData(Document); } } else { swSelMgr = null; prop.GetPropertyData(Document); } d = docT; od = overDocT; }
public void DrawingNoInput() { IModelDoc2 modDoc = (IModelDoc2)iSwApp.ActiveDoc; //获取当前打开文件类型:1-part,2-assembly int modleType = modDoc.GetType(); //将本体命名 GetAndSetDrawingNo(modDoc);//待完善 //装配体则对下层命名 if (modleType == 2) { AssemblyDoc asmDoc = (AssemblyDoc)modDoc; SelectionMgr selectionMgr = modDoc.SelectionManager; IModelDoc2 partDoc; Component2 component; //asmDoc.getsel int looptime = selectionMgr.GetSelectedObjectCount2(-1); while (looptime >= 1) { //todo:校核是否是零件类,现在是直接抛出 try { looptime--; component = selectionMgr.GetSelectedObject6(looptime + 1, -1); partDoc = (IModelDoc2)component.GetModelDoc2(); GetAndSetDrawingNo(partDoc); } catch { } } } }
private void TreeViewJointtreeAfterSelect(object sender, TreeViewEventArgs e) { Font fontRegular = new Font(treeViewJointTree.Font, FontStyle.Regular); Font fontBold = new Font(treeViewJointTree.Font, FontStyle.Bold); if (previouslySelectedNode != null && !previouslySelectedNode.IsBaseNode) { SaveJointDataFromPropertyBoxes(previouslySelectedNode.Link.Joint); } if (previouslySelectedNode != null) { previouslySelectedNode.NodeFont = fontRegular; } LinkNode node = (LinkNode)e.Node; ActiveSWModel.ClearSelection2(true); SelectionMgr manager = ActiveSWModel.SelectionManager; SelectData data = manager.CreateSelectData(); data.Mark = -1; foreach (Component2 component in node.Link.SWComponents) { component.Select4(true, data, false); } node.NodeFont = fontBold; node.Text = node.Text; FillJointPropertyBoxes(node.Link.Joint); previouslySelectedNode = node; }
public void setColour(Color c) { SldWorks swApp = ConnectToSolidWorks(); Component2 swComp = default(Component2); ModelDoc2 swModel = (ModelDoc2)swApp.ActiveDoc; SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager; swComp = swSelMgr.GetSelectedObjectsComponent3(1, 0); var vMatProp = (double[])swComp.MaterialPropertyValues;// GetModelMaterialPropertyValues(""); if (vMatProp == null) { ModelDoc2 swCompModel = (ModelDoc2)swComp.GetModelDoc(); vMatProp = (double[])swCompModel.MaterialPropertyValues; } vMatProp[0] = c.R / 255; vMatProp[1] = c.G / 255; vMatProp[2] = c.B / 255; swComp.MaterialPropertyValues = vMatProp; }
public void InsertBom() { SldWorks swApp = default(SldWorks); ModelDoc2 swModel = default(ModelDoc2); SelectionMgr swSelMgr = default(SelectionMgr); FeatureManager swFeatMgr = default(FeatureManager); SolidWorks.Interop.sldworks.View swView; BomTableAnnotation swBomAnn = default(BomTableAnnotation); BomFeature swBomFeat = default(BomFeature); long anchorType = 0; long bomType = 0; string configuration = null; string tableTemplate = null; object visible = null; DrawingDoc swDraw; Sheet swSheet = default(Sheet); //swApp = DirectCast(Marshal.GetActiveObject("SldWorks.Application"), SldWorks) swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); swModel = swApp.ActiveDoc; swFeatMgr = swModel.FeatureManager; swDraw = (DrawingDoc)swModel; swSheet = swDraw.GetCurrentSheet(); swModel.Extension.SetUserPreferenceString((int)swUserPreferenceStringValue_e.swDetailingLayer, (int)swUserPreferenceOption_e.swDetailingBillOfMaterial, ""); //ecли FALSE вставляются все конфигурации swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swOneConfigOnlyTopLevelBom, 0, false); swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swBomTableDontAddQTYNextToConfigName, 0, true); swModel.Extension.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDontCopyQTYColumnNameFromTemplate, 0, true); //swDraw.SetUserPreferenceIntegerValue(swBomTableZeroQuantityDisplay, swZeroQuantityBlank); //Select View swModel.ClearSelection2(true); swView = swDraw.GetCurrentSheet().GetViews()[0]; //Insert BOM Table anchorType = (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft; bomType = (int)swBomType_e.swBomType_TopLevelOnly; swModel.ClearSelection2(true); configuration = ""; tableTemplate = "C:\\Program Files\\SW-Complex\\Template.sldbomtbt"; swBomAnn = swView.InsertBomTable2(false, -0, -0, (int)anchorType, (int)bomType, configuration, tableTemplate); swFeatMgr.UpdateFeatureTree(); swBomFeat = swBomAnn.BomFeature; var Names = swBomFeat.GetConfigurations(false, visible); visible = true; swBomFeat.SetConfigurations(true, visible, Names); }
public SldWindow(ISldWorks app) { _app = (SldWorks)app; _doc = _app.IActiveDoc2; _seleMgr = _doc.ISelectionManager; AttachEvent(); }
public BodyDrawer(SLDManager app, BodyParam body) { application = app; // Получает ISketchManager объект, который позволяет получить доступ к процедурам эскиза swSketchManager = application.swModel.SketchManager; // Получает ISelectionMgr объект для данного документа, что делает выбранный объект доступным swSelMgr = (SelectionMgr)application.swModel.SelectionManager; this.body = body; }
/// <summary> /// Use this if we're looking at an assembly document. /// </summary> /// <param name="md">A ModelDoc2 object.</param> private void SetupAssy(ModelDoc2 md) { // Get a selection manager. swSelMgr = md.SelectionManager; // connect events ConnectAssemblyEvents(md); // Zap! AssySetup = true; }
public AbstractNAngleDrawer(SLDManager app, BodyParametrs body, BodyDrawer bodyDrawer, double angle) { application = app; this.body = body; this.bodyDrawer = bodyDrawer; deflection_Angle = angle * Math.PI / 180; // Получает ISketchManager объект, который позволяет получить доступ к процедурам эскиза swSketchManager = application.swModel.SketchManager; // Получает ISelectionMgr объект для данного документа, что делает выбранный объект доступным swSelMgr = (SelectionMgr)application.swModel.SelectionManager; }
// Строит или изменяет модель public void Build() { InitAndRunSwApp(); // имена размеров в документе полумуфты string fingerParameter1 = "fingers@Круговой массив1"; string fingerParameter2 = "fingers@Круговой массив2"; string nomianalDiameterParameter = "nominalDiameter@Эскиз1"; // имя полумуфты в сборке (имя компонента верхнего уровня) string assemblyPolumuftaName = "Полумуфта-1"; // Менеджер выделения, выбора SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager; // удалить выделение swModel.ClearSelection2(true); Component2 swComp = assembly.GetComponentByName(assemblyPolumuftaName); // выбрать полумуфту, не добавлять к выбранным, дата?, показать всплывающее кокшко swComp.Select4(false, null, false); int info = 0; // начать изменение полумуфты assembly.EditPart2(false, false, ref info); // получить редактируемую модель ModelDoc2 polumufta = (ModelDoc2)assembly.GetEditTarget(); // установка изменяемых параметров для всех конфигураций polumufta.Parameter(fingerParameter1).SetSystemValue3( countFingers, (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations ); polumufta.Parameter(fingerParameter2).SetSystemValue3( countFingers, (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations ); polumufta.Parameter(nomianalDiameterParameter).SetSystemValue3( nominalDiameter, (int)swSetValueInConfiguration_e.swSetValue_InAllConfigurations ); // ?? bool retVal = polumufta.EditSuppress2(); //Debug.Assert(retVal); // ?? assembly.EditAssembly(); swModel.EditRebuild3(); swModel.ForceRebuild3(false); swModel.ViewZoomtofit2(); }
//Selects components from a list. public static void selectComponents(ModelDoc2 model, List <Component2> components, bool clearSelection = true, int mark = -1) { if (clearSelection) { model.ClearSelection2(true); } SelectionMgr manager = model.SelectionManager; SelectData data = manager.CreateSelectData(); data.Mark = mark; foreach (Component2 component in components) { component.Select4(true, data, false); } }
//Finds the selected components and returns them, used when pulling the items from the selection box because it would be too hard // for SolidWorks to allow you to access the selectionbox components directly. public static void getSelectedComponents(ModelDoc2 model, List <Component2> Components, int Mark = -1) { SelectionMgr selectionManager = model.SelectionManager; Components.Clear(); for (int i = 0; i < selectionManager.GetSelectedObjectCount2(Mark); i++) { object obj = selectionManager.GetSelectedObject6(i + 1, Mark); Component2 comp = (Component2)obj; if (comp != null) { Components.Add(comp); } } }
/// <summary> /// Unhook events in the assembly context. /// </summary> private void DisconnectAssemblyEvents() { // unhook 'em all if (AssmEventsAssigned) { ad.UserSelectionPreNotify -= ad_UserSelectionPreNotify; ad.UserSelectionPostNotify -= ad_UserSelectionPostNotify; ad.DestroyNotify2 -= ad_DestroyNotify2; ad.ActiveDisplayStateChangePostNotify -= ad_ActiveDisplayStateChangePostNotify; ad.ActiveViewChangeNotify -= ad_ActiveViewChangeNotify; swSelMgr = null; } AssmEventsAssigned = false; AssySetup = false; }
//Selects the components of a link. Helps highlight when the associated node is // selected from the tree public static void SelectComponents(ModelDoc2 model, Link Link, bool clearSelection, int mark = -1) { if (clearSelection) { model.ClearSelection2(true); } SelectionMgr manager = model.SelectionManager; SelectData data = manager.CreateSelectData(); data.Mark = mark; SelectComponents(model, Link.SWComponents, false); foreach (Link child in Link.Children) { SelectComponents(model, child, false, mark); } }
public void SaveAs() { IModelDoc2 modDoc = (IModelDoc2)iSwApp.ActiveDoc; ModelDocExtension mDocExten; IModelDoc2 swModel; AssemblyDoc asmDoc = (AssemblyDoc)modDoc; SelectionMgr selectionMgr = modDoc.SelectionManager; Component2 component; string path; string recentPath; int errors = 0; int warnings = 0; recentPath = iSwApp.GetRecentFiles()[0].Substring(0, modDoc.GetPathName().LastIndexOf("\\")); int looptime = selectionMgr.GetSelectedObjectCount2(-1); while (looptime >= 1) { try { looptime--; component = selectionMgr.GetSelectedObject6(looptime + 1, -1); swModel = (IModelDoc2)component.GetModelDoc2(); mDocExten = swModel.Extension; //todo:校核是否是零件类,现在是直接抛出 //另存为对话框 SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "另存为"; sfd.InitialDirectory = recentPath;//更改为最近使用 sfd.Filter = "零件| *.sldprt"; sfd.ShowDialog(); path = sfd.FileName; if (path == "") { return; } //另存为新零件 mDocExten.SaveAs(path, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings); //替换现有零件 asmDoc.ReplaceComponents(path, "", false, true); } catch { } } }
public static void GetFace(ModelDoc2 Doc) { ModelDocExtension DocEx = Doc.Extension; SelectionMgr SwSelMrg = Doc.SelectionManager; DocEx.SelectByID2("", "FACE", -100 / 1000.0, 60 / 1000.0, 15 / 1000.0, false, -1, null, 0); System.Windows.MessageBox.Show("模拟选中面"); string selcount = SwSelMrg.GetSelectedObjectCount2(-1).ToString(); swSelectType_e seltype = (swSelectType_e)SwSelMrg.GetSelectedObjectType3(1, -1); if (seltype == swSelectType_e.swSelFACES) { Face2 SwFace = SwSelMrg.GetSelectedObject6(1, -1); System.Windows.MessageBox.Show("选中数:" + selcount + "\r\n选中类型:" + seltype.ToString() + "\r\n选中面面积:" + SwFace.GetArea().ToString()); } }
public FrmEdge(SwAddin swAddin) { InitializeComponent(); _mSwAddin = swAddin; _swModel = (ModelDoc2)_mSwAddin.SwApp.ActiveDoc; _swSelMgr = (SelectionMgr)_swModel.SelectionManager; _swAsmDoc = (AssemblyDoc)_swModel; _swAsmDoc.NewSelectionNotify += NewSelection; pbEdge11.Image = null; pbEdge12.Image = null; pbEdge21.Image = null; pbEdge22.Image = null; NewSelection(); Show(); }
int p_UserSelectionPostNotify() { ModelDoc2 md = (swApp.ActiveDoc as ModelDoc2); DrawingDoc p = (swApp.ActiveDoc as DrawingDoc); SelectionMgr sMgr = (SelectionMgr)md.SelectionManager; if (sMgr.GetSelectedObject6(1, -1) is BomFeature) { BomFeature bomf = (BomFeature)sMgr.GetSelectedObject6(1, -1); OnSelectedBOM(new AppendEventArgs(string.Format(@"Selected {0}.", bomf.Name))); } System.Runtime.InteropServices.Marshal.ReleaseComObject(sMgr); System.Runtime.InteropServices.Marshal.ReleaseComObject(p); System.Runtime.InteropServices.Marshal.ReleaseComObject(md); System.Runtime.InteropServices.Marshal.ReleaseComObject(swApp); return(0); }
public static void MeasureFace(ModelDoc2 Doc) { ModelDocExtension DocEx = Doc.Extension; SelectionMgr SwSelMrg = Doc.SelectionManager; Measure SwMeasure = DocEx.CreateMeasure(); DocEx.SelectByID2("", "FACE", -100 / 1000.0, 60 / 1000.0, 15 / 1000.0, false, -1, null, 0); DocEx.SelectByID2("", "FACE", 100 / 1000.0, 60 / 1000.0, 15 / 1000.0, true, -1, null, 0); Face2 SwFace1 = SwSelMrg.GetSelectedObject6(1, -1); Face2 SwFace2 = SwSelMrg.GetSelectedObject6(2, -1); Entity[] ents = new Entity[] { (Entity)SwFace1, (Entity)SwFace2 }; SwMeasure.Calculate(ents); System.Windows.MessageBox.Show("中心距:" + (SwMeasure.CenterDistance * 1000).ToString().Trim() + "mm"); }
public static void GetEdge(ModelDoc2 Doc) { ModelDocExtension DocEx = Doc.Extension; SelectionMgr SwSelMrg = Doc.SelectionManager; DocEx.SelectByID2("", "EDGE", 0 / 1000.0, 30 / 1000.0, 75 / 1000.0, false, -1, null, 0); System.Windows.MessageBox.Show("模拟选中边线"); string selcount = SwSelMrg.GetSelectedObjectCount2(-1).ToString(); swSelectType_e seltype = (swSelectType_e)SwSelMrg.GetSelectedObjectType3(1, -1); if (seltype == swSelectType_e.swSelEDGES) { Edge SwEdge = SwSelMrg.GetSelectedObject6(1, -1); SwEdge.Display(1, 1, 0, 0, true);//true变色开,false关闭变色 System.Windows.MessageBox.Show("选中数:" + selcount + "\r\n选中类型:" + seltype.ToString() + "\r\n选中边已变色"); } }
public Feature[] AddTMPBasePlaneFromSelectFace() { Feature[] tempFeatures = new Feature[2]; //连接到Solidworks ModelDoc2 swModel = (ModelDoc2)iSwApp.ActiveDoc; //设定标注尺寸时 不输入值 iSwApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swInputDimValOnCreate, false); // Get the pre-selected planar face Face2 swSelFace = default(Face2); SelectionMgr swSelMgr = (SelectionMgr)swModel.SelectionManager; //获取选择数据 SelectData swSelData = default(SelectData); swSelData = swSelMgr.CreateSelectData(); swSelFace = (Face2)swSelMgr.GetSelectedObject6(1, 1); //var ps = swSelFace.GetTessTriStrips(false); //获取屏幕鼠标选择的那个点 var mousePoint = (double[])swSelMgr.GetSelectionPoint2(1, 1); List <Edge> thisFaceEdgeList = GetSelectFaceEdgeList(swSelFace); swModel.ViewZoomtofit2(); Entity swSelFaceEntity = (Entity)swSelFace; string skFirstName = ""; tempFeatures[0] = DrawnSketchOnFace(swModel, mousePoint, thisFaceEdgeList, swSelFaceEntity, out skFirstName); var t = (double[])swSelFace.Normal; swModel.ClearSelection2(true); swSelFaceEntity.Select4(false, swSelData); return(tempFeatures); }
public void CopyLink() { Clipboard.Clear(); AddinDocument addinDoc = _swAddin.GetActiveDoc(); if (addinDoc == null) { return; } string swDoc = addinDoc.FullFileName; ModelDoc2 swModelDoc = SWHelper.GetDocByFileName(swDoc); // нужно учитывать что браться на редактирование может документ не открытый в PLM. тогда здесь будет null и нужно либо открывать документ, либо работать через DMDocument if (swModelDoc == null) { return; } SelectionMgr mSelectionMgr = swModelDoc.ISelectionManager; String sz = ""; var tp = mSelectionMgr.GetSelectedObjectType3(1, -1); if (tp == (int)swSelectType_e.swSelDIMENSIONS) { IDisplayDimension sel = (IDisplayDimension)mSelectionMgr.GetSelectedObject6(1, 0); sz = sel.GetDimension2(0).FullName; Clipboard.SetText(sz); } /* if (tp == (int)swSelectType_e.swSelNOTES) * { * INote sel = (INote)mSelectionMgr.GetSelectedObject6(1, 0); mSelectionMgr.IGetSelectedObjectsComponent2 * sel * * Annotation swAnn = (Annotation)sel.GetAnnotation(); * swAnn. * ModelDocExtension mde = (ModelDocExtension)swModel.Extension; * int id = mde.GetObjectId(swAnn); * * swFeature.GetNameForSelection(out sz); * }*/ //if (sz.Length != 0) MessageBox.Show(sz); }
public FrmSetParameters(SwAddin swAddin) { InitializeComponent(); bitmap = Properties.Resources.Brush; tabMain.AutoSize = true; KeyDown += FormKeyDown; _mSwAddin = swAddin; _swModel = (ModelDoc2)_mSwAddin.SwApp.ActiveDoc; _swSelMgr = (SelectionMgr)_swModel.SelectionManager; _swAsmDoc = (AssemblyDoc)_swModel; _swAsmDoc.NewSelectionNotify += NewSelection; _swAsmDoc.AddItemNotify += AddNewItem; tabMain.Selected += TabMainTabSelected; tabMain.SelectedIndexChanged += TabMainSelectedIndexChanged; if (!Properties.Settings.Default.SetParentWindow) TopMost = true; Show(); NewSelection(); }
//Event Handlers /// <summary> /// Este metodo detecta la seleccion de un feature y lo expone en un evento /// </summary> private int SwAssy_UserSelectionPostNotify() { try { //Tomar selectionManager. selMgr = (SelectionMgr)SwModel.SelectionManager; //Obtener el feature de lo que fue seleccionado swFeat = (Feature)selMgr.GetSelectedObject6(1, -1); if (swFeat != null) { //Disparar evento. userSelectedFeature?.Invoke(this, swFeat); } return(0); } catch (Exception e) { MessageBox.Show("Error disparando userSelectedFeature en SwAssy_UserSelectionPostNotify: " + e.Message); } return(0); }
public void Main() { IModelDoc2 model = swApp.IActiveDoc2; if (model != null) { SelectionMgr selMgr = model.ISelectionManager; IBody2 body = selMgr.GetSelectedObject6(1, -1) as IBody2; if (body != null) { if (body.GetType() == (int)swBodyType_e.swSheetBody) { if (IsOpenGeometry(body)) { swApp.SendMsgToUser("Selected body is an open geometry"); } else { swApp.SendMsgToUser("Selected body is not an open geometry"); } } else { swApp.SendMsgToUser("Selected body is not a sheet body"); } } else { swApp.SendMsgToUser("Please select sheet body"); } } else { swApp.SendMsgToUser("Please open model"); } return; }
public void PartDye() { IModelDoc2 modDoc = (IModelDoc2)iSwApp.ActiveDoc; //获取当前打开文件类型:1-part,2-assembly int modleType = modDoc.GetType(); dynamic materialPropertyValues; PartDoc partDoc; Component2 component; if (modleType == 1) { partDoc = (PartDoc)modDoc; materialPropertyValues = partDoc.MaterialPropertyValues; partDoc.MaterialPropertyValues = RandomColorValues(materialPropertyValues); } else if (modleType == 2) { AssemblyDoc asmDoc = (AssemblyDoc)modDoc; SelectionMgr selectionMgr = modDoc.SelectionManager; //asmDoc.getsel int looptime = selectionMgr.GetSelectedObjectCount2(-1); while (looptime >= 1) { try { looptime--; component = selectionMgr.GetSelectedObject6(looptime + 1, -1); partDoc = (PartDoc)component.GetModelDoc2(); //todo:校核是否是零件类,现在是直接抛出 materialPropertyValues = partDoc.MaterialPropertyValues; partDoc.MaterialPropertyValues = RandomColorValues(materialPropertyValues); } catch { } } } modDoc.GraphicsRedraw2(); }
public SWTableType(ModelDoc2 md, System.Collections.Specialized.StringCollection sc) { _masterHashes = sc; part = md; swSelMgr = (SelectionMgr)part.SelectionManager; if (part != null && swSelMgr != null) { BomFeature swBom = null; try { swBom = (BomFeature)swSelMgr.GetSelectedObject6(1, -1); } catch { // } if (swBom != null) { fill_table(swBom); } else { find_bom(); } } }
//Selects the components of a link. Helps highlight when the associated node is selected from the tree public static void selectComponents(ModelDoc2 model, link Link, bool clearSelection, int mark = -1) { if (clearSelection) { model.ClearSelection2(true); } SelectionMgr manager = model.SelectionManager; SelectData data = manager.CreateSelectData(); data.Mark = mark; if (Link.SWComponent != null) { Link.SWComponent.Select4(true, data, false); } else { selectComponents(model, Link.SWcomponents, false); } foreach (link child in Link.Children) { selectComponents(model, child, false, mark); } }
public void loadFile() { System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog.InitialDirectory = "C:/Samples"; openFileDialog.Filter = "DMC Files (*.DMC)|*.DMC;*.dmc|STL Files (*.stl, *.STL)|*.stl;*.STL"; openFileDialog.FilterIndex = 2; openFileDialog.RestoreDirectory = false; openFileDialog.Title = "Select File"; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { fileName = openFileDialog.FileName; path = Path.GetDirectoryName(fileName); string extension = new FileInfo(fileName).Extension; switch (extension) { case ".dmc": case ".DMC": LoadedType = fileType.DMC; if (stlLoaded) { tph.SwitchType.Visible = true; tph.SwitchType.Text = "Switch To STL"; } break; case ".stl": case ".STL": LoadedType = fileType.STL; if (stlLoaded) { tph.SwitchType.Visible = true; tph.SwitchType.Text = "Switch To DMC"; } break; default: LoadedType = fileType.None; break; } if (fileName != null) { var reader = new StreamReader(fileName); string partTemplate = iSwApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); if (modDoc == null) { modDoc = (IModelDoc2)iSwApp.NewDocument(partTemplate, (int)swDwgPaperSizes_e.swDwgPaperA2size, 0.0, 0.0); modDoc.ShowNamedView2("*Isometric", -1); swSelectionMgr = modDoc.SelectionManager; vis = new Vis(iSwApp, modDoc); } while (!reader.EndOfStream) { string line = reader.ReadLine(); switch (LoadedType) { case fileType.DMC: scanDMC(line); break; case fileType.STL: scanSTL(line); break; default: break; } } switch (LoadedType) { case fileType.DMC: StartSwLines(); break; case fileType.STL: MakeTriangles(); break; default: break; } } } catch { } } }
public void Setup() { ui = TestUI.Create(); controller = ui.controller; selectionMgr = controller.GetSelectionMgr(); eventDB = controller.GetEventDB(); }
//, ref AttributeDef defattr_chconveyor) public void UpdateFromSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody) { // Fetch current properties from the selected part(s) (i.e. ChBody in C::E) for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++) if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS) { //Component2 swPart = (Component2)swSelMgr.GetSelectedObject6(isel, -1); Component2 swPart = swSelMgr.GetSelectedObjectsComponent3(isel, -1); ModelDoc2 swPartModel = (ModelDoc2)swPart.GetModelDoc2(); Component2 swPartcorr = swPartModel.Extension.GetCorresponding(swPart);// ***TODO*** for instanced parts? does not work... swPartcorr = swPart; // ***TODO*** if (swPartModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { if (swPart.Solving == (int)swComponentSolvingOption_e.swComponentFlexibleSolving) { System.Windows.Forms.MessageBox.Show("Fexible assemblies not supported as ChBody (set as Rigid?)"); return; } if (swPart.Solving == (int)swComponentSolvingOption_e.swComponentRigidSolving) { System.Windows.Forms.MessageBox.Show("Setting props to rigid assembly as ChBody"); AssemblyDoc swAssemblyDoc = (AssemblyDoc)swPartModel; swPart.Select(false); swAssemblyDoc.EditAssembly(); swAssemblyDoc.EditRebuild(); //return; } } // fetch SW attribute with Chrono parameters for ChBody SolidWorks.Interop.sldworks.Attribute myattr = null; if (swPartcorr != null) myattr = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(mdefattr_chbody, 0); if (myattr == null) { // if not already added to part, create and attach it //System.Windows.Forms.MessageBox.Show("Create data"); myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPartcorr, "Chrono::ChBody_data", 0, (int)swInConfigurationOpts_e.swAllConfiguration); swPartModel.ForceRebuild3(false); // needed, but does not work... //swPartModel.Rebuild((int)swRebuildOptions_e.swRebuildAll); // needed but does not work... if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityInvalid)) System.Windows.Forms.MessageBox.Show("swIsEntityInvalid!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntitySuppressed)) System.Windows.Forms.MessageBox.Show("swIsEntitySuppressed!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityAmbiguous)) System.Windows.Forms.MessageBox.Show("swIsEntityAmbiguous!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityDeleted)) System.Windows.Forms.MessageBox.Show("swIsEntityDeleted!"); } Set_collision_on(Convert.ToBoolean(((Parameter)myattr.GetParameter( "collision_on")).GetDoubleValue())); Set_friction(((Parameter)myattr.GetParameter( "friction")).GetDoubleValue()); Set_rolling_friction(((Parameter)myattr.GetParameter( "rolling_friction")).GetDoubleValue()); Set_spinning_friction(((Parameter)myattr.GetParameter( "spinning_friction")).GetDoubleValue()); Set_restitution(((Parameter)myattr.GetParameter( "restitution")).GetDoubleValue()); Set_collision_envelope(((Parameter)myattr.GetParameter( "collision_envelope")).GetDoubleValue()); Set_collision_margin(((Parameter)myattr.GetParameter( "collision_margin")).GetDoubleValue()); Set_collision_family((int)((Parameter)myattr.GetParameter( "collision_family")).GetDoubleValue()); // fetch SW attribute with Chrono parameters for ChConveyor /* SolidWorks.Interop.sldworks.Attribute myattr_conv = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); if (myattr_conv == null) { // if not already added to part, create and attach it //myattr_conv = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono::ChConveyor_data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); } */ /* // fetch SW attribute with Chrono parameters for ChConveyor (if any!) SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); if (myattr_conveyor != null) { show_conveyor_params = true; Set_conveyor_speed(((Parameter)myattr_conveyor.GetParameter( "conveyor_speed")).GetDoubleValue()); } */ } }
//, ref AttributeDef defattr_chconveyor) public void StoreToSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody) { //System.Windows.Forms.MessageBox.Show("StoreToSelection()"); // If user pressed OK, apply settings to all selected parts (i.e. ChBody in C::E): for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++) if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS) { //Component2 swPart = (Component2)swSelMgr.GetSelectedObject6(isel, -1); Component2 swPart = swSelMgr.GetSelectedObjectsComponent3(isel, -1); ModelDoc2 swPartModel = (ModelDoc2)swPart.GetModelDoc2(); Component2 swPartcorr = swPartModel.Extension.GetCorresponding(swPart);// ***TODO*** for instanced parts? does not work... swPartcorr = swPart; // ***TODO*** // fetch SW attribute with Chrono parameters for ChBody SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swPartcorr.FindAttribute(mdefattr_chbody, 0); if (myattr == null) { // if not already added to part, create and attach it System.Windows.Forms.MessageBox.Show("Create data [should not happen here]"); myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPartcorr, "Chrono::ChBody data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); swPartModel.ForceRebuild3(false); // needed? if (myattr == null) System.Windows.Forms.MessageBox.Show("Error: myattr null in setting!!"); } ((Parameter)myattr.GetParameter("collision_on")).SetDoubleValue2( Convert.ToDouble(m_collide), (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("friction")).SetDoubleValue2( m_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("rolling_friction")).SetDoubleValue2( m_rolling_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("spinning_friction")).SetDoubleValue2( m_spinning_friction, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("restitution")).SetDoubleValue2( m_restitution, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_margin")).SetDoubleValue2( m_collision_margin, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_envelope")).SetDoubleValue2( m_collision_envelope, (int)swInConfigurationOpts_e.swThisConfiguration, ""); ((Parameter)myattr.GetParameter("collision_family")).SetDoubleValue2( (double)m_collision_family, (int)swInConfigurationOpts_e.swThisConfiguration, ""); /* // fetch SW attribute with Chrono parameters for ChConveyor SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); if (myattr_conveyor == null) { // if not already added to part, create and attach it myattr_conveyor = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono ChConveyor data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); if (myattr_conveyor == null) System.Windows.Forms.MessageBox.Show("myattr null in setting!!"); } ((Parameter)myattr_conveyor.GetParameter("conveyor_speed")).SetDoubleValue2( m_conveyor_speed, (int)swInConfigurationOpts_e.swThisConfiguration, ""); */ } }
/// <summary> /// Méthode interne. /// Initialiser l'objet GestDeSelection. /// </summary> /// <param name="Modele"></param> /// <returns></returns> internal Boolean Init(SelectionMgr SwGestionnaire, eModele Modele) { Log.Methode(cNOMCLASSE); if ((SwGestionnaire != null) && (Modele != null) && Modele.EstInitialise) { _SwGestDeSelection = SwGestionnaire; _Modele = Modele; _EstInitialise = true; } else { Log.Message("!!!!! Erreur d'initialisation"); } return _EstInitialise; }
//, ref AttributeDef defattr_chconveyor) public void UpdateFromSelection(SelectionMgr swSelMgr, ref AttributeDef mdefattr_chbody) { // Fetch current properties from the selected part(s) (i.e. ChBody in C::E) for (int isel = 1; isel <= swSelMgr.GetSelectedObjectCount2(-1); isel++) if ((swSelectType_e)swSelMgr.GetSelectedObjectType3(isel, -1) == swSelectType_e.swSelCOMPONENTS) { Component2 swPart = (Component2)swSelMgr.GetSelectedObject6(isel, -1); ModelDoc2 swPartModel = (ModelDoc2)swPart.GetModelDoc(); // fetch SW attribute with Chrono parameters for ChBody SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(mdefattr_chbody, 0); if (myattr == null) { // if not already added to part, create and attach it myattr = mdefattr_chbody.CreateInstance5(swPartModel, swPart, "Chrono::ChBody_data", 0, (int)swInConfigurationOpts_e.swAllConfiguration); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityInvalid)) System.Windows.Forms.MessageBox.Show("swIsEntityInvalid!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntitySuppressed)) System.Windows.Forms.MessageBox.Show("swIsEntitySuppressed!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityAmbiguous)) System.Windows.Forms.MessageBox.Show("swIsEntityAmbiguous!"); if (myattr.GetEntityState((int)swAssociatedEntityStates_e.swIsEntityDeleted)) System.Windows.Forms.MessageBox.Show("swIsEntityDeleted!"); swPartModel.ForceRebuild3(false); // needed? } Set_collision_on(Convert.ToBoolean(((Parameter)myattr.GetParameter( "collision_on")).GetDoubleValue())); Set_friction(((Parameter)myattr.GetParameter( "friction")).GetDoubleValue()); Set_rolling_friction(((Parameter)myattr.GetParameter( "rolling_friction")).GetDoubleValue()); Set_spinning_friction(((Parameter)myattr.GetParameter( "spinning_friction")).GetDoubleValue()); Set_restitution(((Parameter)myattr.GetParameter( "restitution")).GetDoubleValue()); Set_collision_envelope(((Parameter)myattr.GetParameter( "collision_envelope")).GetDoubleValue()); Set_collision_margin(((Parameter)myattr.GetParameter( "collision_margin")).GetDoubleValue()); Set_collision_family((int)((Parameter)myattr.GetParameter( "collision_family")).GetDoubleValue()); // fetch SW attribute with Chrono parameters for ChConveyor /* SolidWorks.Interop.sldworks.Attribute myattr_conv = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); if (myattr_conv == null) { // if not already added to part, create and attach it //myattr_conv = defattr_chconveyor.CreateInstance5(swPartModel, swPart, "Chrono::ChConveyor_data", 0, (int)swInConfigurationOpts_e.swThisConfiguration); } */ /* // fetch SW attribute with Chrono parameters for ChConveyor (if any!) SolidWorks.Interop.sldworks.Attribute myattr_conveyor = (SolidWorks.Interop.sldworks.Attribute)swPart.FindAttribute(defattr_chconveyor, 0); if (myattr_conveyor != null) { show_conveyor_params = true; Set_conveyor_speed(((Parameter)myattr_conveyor.GetParameter( "conveyor_speed")).GetDoubleValue()); } */ } }