/// <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; }
/// <summary> /// Toss out old events and reconnect the Redbrick to the new doc. /// </summary> /// <returns>0. Every time.</returns> int SwApp_ActiveDocChangeNotify() { if (SwApp == null) { SwApp = RequestSW(); } Document = SwApp.ActiveDoc; if (!(Document.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) && AssySetup) { DisconnectAssemblyEvents(); } if (!(Document.GetType() == (int)swDocumentTypes_e.swDocPART) && PartSetup) { DisconnectPartEvents(); } if (!(Document.GetType() == (int)swDocumentTypes_e.swDocDRAWING) && DrawSetup) { DisconnectDrawingEvents(); } ConnectSelection(); return(0); }
// Set Materials public void ApplyMaterial(string partPath, string confName, int materialID, SldWorks swapp) { _swmodel = swapp.ActiveDoc; swapp.SetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swFileLocationsMaterialDatabases, GlobalPaths.PathToSwComplexFolder); // задаем базы данных материалов _swPartDoc = ((PartDoc)(_swmodel)); const string dbMatName = "vents-materials.sldmat"; ToSQL addMatXml = new ToSQL(); if (_swmodel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { Component2 comp = _swmodel.ISelectionManager.GetSelectedObject3(1); PartDoc swPartAssem = comp.GetModelDoc(); //// удаляем материал //swPartAssem.SetMaterialPropertyName("", ""); // применяем материал swPartAssem.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(materialID)); _swmodel.ClearSelection2(true); } else if (_swmodel.GetType() == (int)swDocumentTypes_e.swDocPART) { // Если имя не пустое if (partPath != "") { //// удаляем материал //swPartDoc.SetMaterialPropertyName("", ""); // применяем материал _swPartDoc.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(materialID)); //_swmodel.ForceRebuild3(false); //_swmodel.Save3((int)swSaveAsOptions_e.swSaveAsOptions_Silent, 0, 0); //swapp.CloseDoc(partPath); //swapp.ExitApp(); //swapp = null; } else { //// удаляем материал //swPartDoc.SetMaterialPropertyName(confName, ""); // применяем материал _swPartDoc.SetMaterialPropertyName2(confName, dbMatName, addMatXml.AddMaterialtoXml(materialID)); } } //catch (Exception ex) //{ // //swapp.SendMsgToUser(ex.ToString()); // MessageBox.Show(ex.Message); // Error = ex.ToString(); //} }
/// <summary> /// Hook up events for the assembly context. /// </summary> /// <param name="md">A ModelDoc2 object.</param> private void ConnectAssemblyEvents(ModelDoc2 md) { if ((md.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) && !AssmEventsAssigned) { ad = (AssemblyDoc)md; ad.UserSelectionPreNotify += ad_UserSelectionPreNotify; // user clicks part/subassembly ad.UserSelectionPostNotify += ad_UserSelectionPostNotify; // doc closing, I think. ad.DestroyNotify2 += ad_DestroyNotify2; // Not sure, and not implemented yet. ad.ActiveDisplayStateChangePostNotify += ad_ActiveDisplayStateChangePostNotify; // switching docs ad.ActiveViewChangeNotify += ad_ActiveViewChangeNotify; DisconnectDrawingEvents(); AssmEventsAssigned = true; } else { // We're already set up, I guess. } }
public int CheckDrawingDoc() { var functionReturnValue = 0; try { swModel = SwApp.ActiveDoc; try { if ((swModel.GetType() != (int)swDocumentTypes_e.swDocDRAWING)) { functionReturnValue = 0; } else { functionReturnValue = 1; } } catch { functionReturnValue = 0; } } catch (Exception ex) { MessageBox.Show(ex.Message); } return(functionReturnValue); }
public static void GetDocObject(SldWorks iswApp) { StringBuilder sb = new StringBuilder(""); ModelDoc2 SwDoc = iswApp.ActiveDoc;//获得当前激活的文档 sb.Append("文档:" + SwDoc.GetTitle() + "\r\n"); int DocType = SwDoc.GetType(); //获得激活的文档类型 if (DocType == (int)swDocumentTypes_e.swDocPART) //若类型是零件 { PartDoc SwPart = (PartDoc)SwDoc; sb.Append("文档类型:零部件\r\n"); } else if (DocType == (int)swDocumentTypes_e.swDocASSEMBLY)//若类型是装配体 { AssemblyDoc SwAssem = (AssemblyDoc)SwDoc; sb.Append("文档类型:装配体\r\n"); } else if (DocType == (int)swDocumentTypes_e.swDocDRAWING)//若类型是工程图 { DrawingDoc SwAssem = (DrawingDoc)SwDoc; sb.Append("文档类型:工程图\r\n"); } ModelDocExtension SwDocEx = SwDoc.Extension;//获得扩展文档对象 if (SwDocEx != null) { sb.Append("扩展文档:已获得"); } MessageBox.Show(sb.ToString().Trim()); }
public static void GetChildrenComp(ModelDoc2 Doc) { if (Doc.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { AssemblyDoc Assem = (AssemblyDoc)Doc; #region 顶底层零部件 StringBuilder topsb = new StringBuilder("顶层部件:\r\n"); object[] Comps = Assem.GetComponents(true); foreach (object cp in Comps) { topsb.Append(((Component2)cp).Name2 + "\r\n"); } #endregion #region 所有零部件 StringBuilder allsb = new StringBuilder("所有部件:\r\n"); Comps = Assem.GetComponents(false); foreach (object cp in Comps) { allsb.Append(((Component2)cp).Name2 + "\r\n"); } #endregion System.Windows.MessageBox.Show(topsb + "\r\n" + allsb); } }
public int LoadSPropEnable() { var functionReturnValue = 0; try { swModel = SwApp.ActiveDoc; try { if (swModel.GetType() == (int)swDocumentTypes_e.swDocDRAWING) { functionReturnValue = 0; } else { functionReturnValue = 1; } } catch { functionReturnValue = 0; } } catch (Exception ex) { MessageBox.Show(ex.Message); } return(functionReturnValue); }
//<~~~~~~ При открытом чертеже кнопка погашена public int LoadMaterialsEnable() { var functionReturnValue = 0; try { //SwApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); swModel = SwApp.ActiveDoc; try { if ((swModel.GetType() != (int)swDocumentTypes_e.swDocPART)) { functionReturnValue = 0; } else { functionReturnValue = 1; } } catch { functionReturnValue = 0; } } catch (Exception ex) { MessageBox.Show(ex.Message); } return(functionReturnValue); }
public int NotificationOfChangesEnable() { var functionReturnValue = 0; try { swModel = SwApp.ActiveDoc; try { if (swModel.GetType() != (int)swDocumentTypes_e.swDocDRAWING) { functionReturnValue = 0; } else { functionReturnValue = 1; } } catch { functionReturnValue = 0; } } catch (Exception ex) { MessageBox.Show(ex.Message + "; " + ex.StackTrace); } return(functionReturnValue); }
public void SelectFeature(ModelDoc2 document, string featureName, string instanceId, string itemType) // ReSharper restore UnusedMember.Global { String processedName = ""; if (itemType != "COMPONENT") { if ((FileType)document.GetType() != FileType.Assembly) { throw new SolidWorksException(String.Format("Cannot select component {0} because current document is not an assembly.", featureName)); } if (!string.IsNullOrEmpty(instanceId)) { processedName = String.Format("{0}-{1}", featureName, instanceId); } String temp = (from Component2 component in (document as AssemblyDoc).GetComponents(true) as IEnumerable <Component2> where component.Name.ToUpper() == processedName.ToUpper() select component.Name).First(); processedName = String.Format("{0}@{1}", temp, Path.GetFileNameWithoutExtension(document.GetPathName())); } else { processedName = (from Feature feature in document.FeatureManager.GetFeatures(true) as IEnumerable <Feature> where feature.Name.ToUpper() == featureName.ToUpper() select feature.Name).First(); } if (!document.Extension.SelectByID(processedName, itemType, 0, 0, 0, false, 0, null)) { throw new SolidWorksException(String.Format("Selected feature ({0}) does not exist.", featureName)); } }
public static bool GetSolidWorks3D(SldWorks swApp, out ModelDoc2 swModel) { try { // Присваиваем переменной ссылку на запущенный solidworks (по названию) swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); } catch { // Отображает окно сообщения с заданным текстом swModel = null; return(false); } if (swApp.ActiveDoc == null) { // Отображает окно сообщения с заданным текстом swModel = null; return(false); } // Присваиваем переменной ссылку на открытый активный проект в SolidWorks swModel = (ModelDoc2)swApp.ActiveDoc; // Проверка на открытие именно детали в SolidWorks if (swModel.GetType() != (int)swDocumentTypes_e.swDocPART) { return(false); } return(true); }
public bool CheckSheetMetal() { swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); swModel = swApp.ActiveDoc; // finish writing checking on null var PartSheetMetal = true; if (swModel.GetType() == (int)swDocumentTypes_e.swDocPART) { swPartDoc = (PartDoc)swModel; Body2 swbody; object[] vbodies = swPartDoc.GetBodies2((int)swBodyType_e.swSolidBody, false); for (int i = 0; i < vbodies.Length; i++) { swbody = (Body2)vbodies[i]; if (swbody.IsSheetMetal()) { PartSheetMetal = true; } else { PartSheetMetal = false; } } } return(PartSheetMetal); }
private Boolean DocCheck() { if (swModel == null) { ExportPDFException e = new ExportPDFException("You must have a drawing document open."); return(false); } else if ((Int32)swModel.GetType() != (Int32)swDocumentTypes_e.swDocDRAWING) { ExportPDFException e = new ExportPDFException("You must have a drawing document open."); return(false); } else if (swModel.GetPathName() == String.Empty) { swModel.Extension.RunCommand((int)swCommands_e.swCommands_SaveAs, swModel.GetTitle()); if (swModel.GetPathName() == string.Empty) { return(false); } return(true); } else { return(true); } }
private void GetChildren(JSolidworksAsemble _JswDoc) { //this.Parts.Add((JSolidworksAsemble)_JswDoc); //先将此文件加入到子零部件列表中 //如果是装配体 if (_JswDoc.swDoc == null) { _JswDoc.Load(); } Configuration swConf = (Configuration)_JswDoc.swDoc.GetActiveConfiguration(); if (swConf == null) { return; } Component2 swRootComp = (Component2)swConf.GetRootComponent(); if (swRootComp == null) { return; } else { object[] Children_List = swRootComp.GetChildren(); foreach (object _doc in Children_List) { ModelDoc2 t_doc = ((Component2)_doc).GetModelDoc2(); if (t_doc.GetType() == (int)swDocumentTypes_e.swDocPART) { //子件是 string _Path = t_doc.GetPathName(); JSolidworksPart JPart = new JSolidworksPart(t_doc.GetPathName()); JPart.Load(); _JswDoc.Parts.Add(JPart); } else { if (t_doc.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { JSolidworksAsemble JPart = new JSolidworksAsemble(t_doc.GetPathName()); JPart.Load(); _JswDoc.Parts.Add(JPart); } } } } return; }
public static void GetSolidObject() { swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); swModel = swApp.ActiveDoc; docType = (swDocumentTypes_e)swModel.GetType(); configName = swModel.GetActiveConfiguration().Name;//при первом вызове присваеваеться активная конфигурация Class.configNames = Class.GetAllConfigurations(out lockForConf); }
/// <summary> /// Class constructor /// </summary> /// <param name="swModel">Модель документа</param> public SwModelManager(ModelDoc2 swModel) { if (!(swModel is null)) { _swModel = swModel; DocType = (swDocumentTypes_e)swModel.GetType(); Debug.Print("SwModelManager: SwModel initialised"); }
internal void GetPropertyBox(string configname) { const long valueset = 1000;; const int swDocPart = 1; const int swDocAssembly = 2; _swapp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); _swmodel = _swapp.ActiveDoc; Configuration swConf = _swmodel.GetConfigurationByName(configname); if (swConf.IsDerived() == false) { //swmodel.ShowConfiguration2(configname); _swmodel.EditRebuild3(); if (_swmodel.GetType() == swDocPart) { var part = (PartDoc)_swmodel; var box = part.GetPartBox(true); _swmodel.AddCustomInfo3(configname, "Длина", 30, ""); _swmodel.AddCustomInfo3(configname, "Ширина", 30, ""); _swmodel.AddCustomInfo3(configname, "Высота", 30, ""); _swmodel.CustomInfo2[configname, "Длина"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(box[0] - box[3]) * valueset), 0)); _swmodel.CustomInfo2[configname, "Ширина"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(box[1] - box[4]) * valueset), 0)); _swmodel.CustomInfo2[configname, "Высота"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(box[2] - box[5]) * valueset), 0)); } else if (_swmodel.GetType() == swDocAssembly) { var swAssy = (AssemblyDoc)_swmodel; var boxAss = swAssy.GetBox((int)swBoundingBoxOptions_e.swBoundingBoxIncludeRefPlanes); _swmodel.AddCustomInfo3(configname, "Длина", 30, ""); _swmodel.AddCustomInfo3(configname, "Ширина", 30, ""); _swmodel.AddCustomInfo3(configname, "Высота", 30, ""); _swmodel.CustomInfo2[configname, "Длина"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(boxAss[0] - boxAss[3]) * valueset), 0)); _swmodel.CustomInfo2[configname, "Ширина"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(boxAss[1] - boxAss[4]) * valueset), 0)); _swmodel.CustomInfo2[configname, "Высота"] = Convert.ToString(Math.Round(Convert.ToDecimal(Math.Abs(boxAss[2] - boxAss[5]) * valueset), 0)); } } }
public void PrepareTT(string swDoc, InfoObject ioVersion) { // Чтение атрибутов ИО ПЛМ и запись в кэш var TecchReqGrig = ioVersion.GetAttribute("TecchReqGrig").CollectionElements.OrderBy(i => i.GetValue <int>("IndOrder")); var count = TecchReqGrig.Count(); arrTT.Clear(); arrLinks.Clear(); notes.Clear(); foreach (var element in TecchReqGrig) { //MessageBox.Show(element.GetValue<string>("ttElementLabel")); InfoObject childio = element.GetValue <InfoObject>("ChildIO"); arrTT.Add(childio.GetValue <string>("TextLabel")); // Поиск в элементе ТТ атрибутов типа "Значения" и сохранение их в кэш для синхронизации в ПЛМ var SizeList = childio.GetAttribute("SizeList").CollectionElements; foreach (var sz in SizeList) { arrLinks.Add(new ValElem() { link = sz.GetValue <string>("ttElementSolidSizeLink"), val = "" }); } } // Получение документа SW ModelDoc2 Doc = SWHelper.GetDocByFileName(swDoc); // нужно учитывать что браться на редактирование может документ не открытый в PLM. тогда здесь будет null и нужно либо открывать документ, либо работать через DMDocument if (Doc != null) { // Определяем тип документа. Пока рисуем ТТ только на чертежах int docType = Doc.GetType(); switch (docType) { case (int)swDocumentTypes_e.swDocPART: Debug.Print("swPart"); // отрисовка ТТ на основе атрибутов //PaintNoteOnPart(Doc, arrTT.ToArray()); break; case (int)swDocumentTypes_e.swDocDRAWING: Debug.Print("swDraw"); // Расчёт расположения примечаний на основе атрибутов PreCalcNote(Doc, arrTT.ToArray()); // отрисовка ТТ PaintNoteOnDraw(Doc); break; case (int)swDocumentTypes_e.swDocASSEMBLY: Debug.Print("swAssy"); break; default: //swDocNONE, swDocSDM Debug.Print("another doc"); break; } } }
/// <summary> /// Вызывается в процессе сохранения документа в PLM /// </summary> /// <param name="swDoc">документ</param> /// <param name="ioVersion">ио версии в плм</param> public void OnCheckIn(string swDoc, InfoObject ioVersion) { //MessageBox.Show("CheckIn"); SWDocument addinDoc = AddinDocumentCache.ReturnDocument(swDoc, null) as SWDocument; // SWDocument - обёртка документа для использования аддином //addinDoc.GetStatus() - определение plm-статуса документа -не сохранен, сохранён, на редактировании, забблокирован. если документ сохранён в плм, свойства PlmDocument и PlmVersion будут содержать ссылки на ио соответственно документа и версии ModelDoc2 Doc = SWHelper.GetDocByFileName(swDoc); // нужно учитывать что сохраняться может документ не открытый в PLM. тогда здесь будет null и нужно либо открывать документ, либо работать через DMDocument if (Doc != null) { // Определяем тип документа. Пока работаем только с чертежами int docType = Doc.GetType(); if (docType == (int)swDocumentTypes_e.swDocDRAWING) { // Ищем в примечании ТТ по кэшу сохранённых ссылок на значения чертежа. // Если находим, то ищем в чертеже соответствующий элемент и считываем его значение для передачи в ПЛМ. // Заполненные значения передаём в ПЛМ. var TecchReqGrig = ioVersion.GetAttribute("TecchReqGrig").CollectionElements; String notetxt = GetNoteTTtext(Doc); foreach (var sz in arrLinks) { String szval = ""; if (notetxt.Contains(sz.link)) { IDimension d1 = (IDimension)Doc.Parameter(sz.link); if (d1 != null) { szval = d1.Value.ToString(); // d1.GetUserValueIn(swDoc).ToString(); } } if (szval != "") { // Ищем ссылку на размер по всем строкам грида ТТ foreach (var element in TecchReqGrig) { InfoObject childio = element.GetValue <InfoObject>("ChildIO"); // Поиск в элементе ТТ атрибутов типа "Значения" и сохранение их значения из чертежа var SizeList = childio.GetAttribute("SizeList").CollectionElements; foreach (var isz in SizeList) { if (sz.link == isz.GetValue <string>("ttElementSolidSizeLink")) { isz["ttElementSolidSizeText"] = szval; childio.Invoke("RecalcVisibleText", null); element["ttElementValue"] = childio.GetAttribute("VisibleLabel").GetValue(); } } } } } } } Trace.TraceInformation(@"OnCheckIn: document:" + swDoc + " ioVersion: " + ioVersion.ToString()); //Trace.TraceInformation(@"OnCheckIn: SWDocument:" + addinDoc.ToString()); }
int m; // 0 - Деталь, 1 - Сборка private void BindingComboBoxPartition() { try { SwApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); SwModel = SwApp.ActiveDoc; var itemsArrayPart = new[] { "Стандартные изделия", "Прочие изделия", "Материалы", "Комплекты", "ЭМ-Стандартные изделия", "ЭМ-Прочие изделия", "ЭМ-Материалы" }; var itemsArrayAssembly = new[] { "Стандартные изделия", "Прочие изделия", "Комплекты", "ЭМ-Стандартные изделия", "ЭМ-Прочие изделия" }; string[] itemsArray; if ((SwModel.GetType() == (int)swDocumentTypes_e.swDocPART)) { itemsArray = itemsArrayPart; m = 0; } else { itemsArray = itemsArrayAssembly; m = 1; } CboChangePartition.ItemsSource = itemsArray; var activConfiguration = SwModel.ConfigurationManager.ActiveConfiguration.Name; var getCustomProp = SwModel.Extension.CustomPropertyManager[activConfiguration]; var nameProp = getCustomProp.Get("Раздел"); var activPartition = itemsArray.Select(s => nameProp); foreach (var x in from x in itemsArray let enumerable = (string[])(activPartition as string[] ?? activPartition.ToArray()) where x == enumerable.LastOrDefault() select x) { CboChangePartition.Text = x; } if (CboChangePartition.Text == "") { DgMatProp.Visibility = Visibility.Hidden; } } catch (Exception ex) { MessageBox.Show($"Message: {ex.Message}\r\nTargetSite: {ex.TargetSite}\r\nStackTrace: {ex.StackTrace}"); } }
public static void GetPropsFromModelFromDRW() { // подтягиваем свойства из модельки в чертеж swModel = swView.ReferencedDocument; docType = (swDocumentTypes_e)swModel.GetType(); EditProp.configuracione = swView.ReferencedConfiguration; EditProp.FixPropertys(); EditProp.GetProperties(EditProp.configuracione); swModel = swApp.ActiveDoc; // дальше опять работаем с чертежом EditProp.configuracione = ""; docType = (swDocumentTypes_e)swModel.GetType(); }
public static void Set_transparency(ModelDoc2 swModel, string name) { AssemblyDoc swAssembly = null; Component2 swComp = null; ModelDoc2 swCompDoc = null; bool boolstatus = false; try { if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { swModel.ClearSelection2(true); // boolstatus = swModel.Extension.SelectByID2(name + "@" + docname, "COMPONENT", 0, 0, 0, true, 0, null, 0); // SelectionMgr SwSelMgr = swModel.SelectionManager; swAssembly = (AssemblyDoc)swModel; var Components = swAssembly.GetComponents(false); for (int i = 0; i < Components.Length; i++) { //swComp = swAssembly.GetComponentByName(name); swComp = Components[i]; if (swComp != null) { if (swComp.Name2.Contains(name)) { // MessageBox.Show(name); var vMatProps = swComp.MaterialPropertyValues; if (vMatProps == null) { swCompDoc = swComp.GetModelDoc(); if (swCompDoc == null) { return; } vMatProps = swCompDoc.MaterialPropertyValues; } vMatProps[7] = 1; //Transparency swComp.MaterialPropertyValues = vMatProps; swModel.ClearSelection2(true); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } }
private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { this.Close(); } else if (e.Key == Key.S && e.KeyboardDevice.IsKeyDown(Key.LeftCtrl)) { SaveAll(); } else if (e.Key == Key.F5) { SwModel = (ModelDoc2)SwApp.ActiveDoc; if (SwModel != null) { if (((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocPART) && ((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)) { MessageBox.Show("当前文件不是零件或装配体文件!"); Environment.Exit(0); } } else { MessageBox.Show("请打开零件或装配体文件!"); Environment.Exit(0); } SwConfigMgr = SwModel.ConfigurationManager; SwModelExt = SwModel.Extension; SwCustPropMgr = SwModelExt.get_CustomPropertyManager(""); string[] configNames = null; configNames = (string[])SwModel.GetConfigurationNames(); CboxConfigName.Items.Clear(); for (int i = 0; i < configNames.Length; i++) { CboxConfigName.Items.Add(configNames[i]); if (configNames[i].Contains(SwConfigMgr.ActiveConfiguration.Name)) { CboxConfigName.Text = SwConfigMgr.ActiveConfiguration.Name; } } DatePickerDesignDate.SelectedDate = DateTime.Today; TextColorReset(); TextBlock.Text = "已成功连接到SolidWorks文件! 按F5重新载入!"; } }
public static List <object> GetSelectedFaces(SldWorks swApplication, ModelDoc2 swModel) { swModel = swApplication.ActiveDoc; var swSafeEntityList = new List <object>(); var modelType = swModel.GetTitle(); var documentType = (swDocumentTypes_e)swModel.GetType(); if (documentType == swDocumentTypes_e.swDocPART) { var myPartDoc = (PartDoc)swModel; Array myBodyVar = myPartDoc.GetBodies2((int)swBodyType_e.swAllBodies, true); int myBodyCount = 0; for (myBodyCount = myBodyVar.GetLowerBound(0); myBodyCount <= myBodyVar.GetUpperBound(0); myBodyCount++) { var myBodyComparison = (Body2)myBodyVar.GetValue(myBodyCount); var swFace = (Face2)myBodyComparison.GetFirstFace(); while (swFace != null) { var idNode = swFace.GetHashCode(); swFace.SetFaceId(idNode); swFace = swFace.GetNextFace(); } } var mySelManager = (SelectionMgr)swModel.SelectionManager; var selectionCount = mySelManager.GetSelectedObjectCount2(-1); //swApplication.SendMsgToUser("Numero oggetti selezionati " + selectionCount.ToString()); for (int i = 0; i < selectionCount; i++) { var myFace = (Face2)mySelManager.GetSelectedObject6(i + 1, -1); // var idNode = myFace.GetHashCode(); // myFace.SetFaceId(idNode); var swEntity = ((Entity)myFace).GetSafeEntity(); var swSafeEntity = (Entity)swEntity.GetSafeEntity(); swSafeEntityList.Add(swSafeEntity); } } //var listFace = new List<Face2>(); //swApplication.SendMsgToUser("Lista facce " + listFace.Count.ToString()); //foreach (Face2 face2 in listFace) //{ // swApplication.SendMsgToUser("Id: " + face2.GetFaceId().ToString()); //} //ColorFace.KLColorFace(listFace, swApplication); return(swSafeEntityList); }
public SwDrawing(ModelDoc2 drawModel) //Инициализация из класса модели { _drawModel = drawModel; if (_drawModel.GetType() == (int)DocType) { _swApp = SwProcess.swApp; _swDraw = (DrawingDoc)_drawModel; Debug.Print("SwDrawing initialised"); } else { throw new System.TypeLoadException("Модель не является чертежом"); } }
public SWglTFModel ConvertToglTFModel(ModelDoc2 swModel, out ErrorType errors) { SWglTFModel model = null; errors = ErrorType.DoNotKnow; ProgressStatus_event(0.01, "开始读取", ErrorType.NoErros); swDocumentTypes_e ModelType = (swDocumentTypes_e)swModel.GetType(); switch (ModelType) { case swDocumentTypes_e.swDocNONE: errors = ErrorType.NoPartOrAssemblyDocument; return(null); case swDocumentTypes_e.swDocPART: ProgressStatus_event(0.02, "读取零件信息", ErrorType.NoErros); model = ConvertPartToglTF(swModel); ProgressStatus_event(0.5, "读取零件信息完成", ErrorType.NoErros); break; case swDocumentTypes_e.swDocASSEMBLY: ProgressStatus_event(0.02, "读取装配体信息", ErrorType.NoErros); model = ConvertAssemblyToglTF(swModel); ProgressStatus_event(0.5, "读取装配体信息完成", ErrorType.NoErros); break; case swDocumentTypes_e.swDocDRAWING: errors = ErrorType.NoPartOrAssemblyDocument; return(null); case swDocumentTypes_e.swDocSDM: errors = ErrorType.NoPartOrAssemblyDocument; return(null); case swDocumentTypes_e.swDocLAYOUT: errors = ErrorType.NoPartOrAssemblyDocument; return(null); case swDocumentTypes_e.swDocIMPORTED_PART: break; case swDocumentTypes_e.swDocIMPORTED_ASSEMBLY: break; } if (model == null) { errors = ErrorType.DoNotKnow; } return(model); }
private void traverse(Component2 comp) { object[] childrens = comp.GetChildren(); foreach (Component2 child in childrens) { traverse(child); } ModelDoc2 mdocChild = comp.GetModelDoc2(); if (mdocChild.GetType() == 1) { // Bezeichnung kann über 2 Möglichkeiten erfolgen // Dateiname (mit GetFileName wird nur der Dateiname aus einem Dateipfad extrahiert string entry = System.IO.Path.GetFileName(comp.GetPathName()); // oder string entry2 = comp.Name2; //entfernen der 2 hinteren Zeichen im String entry2 = entry2.Remove(entry2.Length - 2); int Row = 0; // überprüfen, ob aktueller Eintrag bereits vorhanden ist, wenn ja Zeilen-Index speichern for (int i = 2; i < index; i++) { if ((string)exlSheet.Cells[i, 3].Value2 == entry) { Row = i; } } // wenn Zeilen Index gesetzt wurde, Wert für Anzahl aus Zeile lesen und um 1 erhöhen // erhöhten Wert in Zelle schreiben if (Row > 0) { double newCount = (double)exlSheet.Cells[Row, 1].Value2 + 1; exlSheet.Cells[Row, 1] = newCount; } else { // Wenn ZeilenIndex nicht gesetzt wurde, neuen Dateipfad exlSheet.Cells[index, 1] = 1; exlSheet.Cells[index, 2] = "Stück"; exlSheet.Cells[index, 3] = entry; lb_output.Items.Add(entry); index++; } } }
/// <summary> /// Hook up events in the part document context. /// </summary> /// <param name="md">A ModelDoc2 object.</param> private void ConnectPartEvents(ModelDoc2 md) { if (md.GetType() == (int)swDocumentTypes_e.swDocPART && !PartEventsAssigned) { pd = (PartDoc)md; // When the config changes, the app knows. pd.ActiveConfigChangePostNotify += pd_ActiveConfigChangePostNotify; pd.FileSavePostNotify += pd_FileSavePostNotify; //pd.ChangeCustomPropertyNotify += pd_ChangeCustomPropertyNotify; pd.DestroyNotify2 += pd_DestroyNotify2; //pd.RegenNotify += pd_RegenNotify; DisconnectDrawingEvents(); PartEventsAssigned = true; } }
private void Reset() { SwApp = new SldWorks(); if (SwApp == null) { MessageBox.Show("未找到已启动的Solidworks主程序!"); Environment.Exit(0); } SwApp.Visible = true; SwModel = (ModelDoc2)SwApp.ActiveDoc; if (SwModel != null) { if (((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocPART) && ((int)SwModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)) { MessageBox.Show("当前文件不是零件或装配体文件!"); Environment.Exit(0); } } else { MessageBox.Show("请打开零件或装配体文件!"); Environment.Exit(0); } SwConfigMgr = SwModel.ConfigurationManager; SwModelExt = SwModel.Extension; SwCustPropMgr = SwModelExt.get_CustomPropertyManager(""); string[] configNames = null; configNames = (string[])SwModel.GetConfigurationNames(); CboxConfigName.Items.Clear(); for (int i = 0; i < configNames.Length; i++) { CboxConfigName.Items.Add(configNames[i]); if (configNames[i].Contains(SwConfigMgr.ActiveConfiguration.Name)) { //cboxConfigName.SelectedIndex = i; CboxConfigName.Text = SwConfigMgr.ActiveConfiguration.Name; } } DatePickerDesignDate.SelectedDate = DateTime.Today; TextColorReset(); TextBlock.Text = "已成功连接到SolidWorks文件! 按F5重新载入!"; }
public bool AttachModelDocEventHandler(ModelDoc2 modDoc) { if (modDoc == null) return false; DocumentEventHandler docHandler = null; if (!openDocs.Contains(modDoc)) { switch (modDoc.GetType()) { case (int)swDocumentTypes_e.swDocPART: { docHandler = new PartEventHandler(modDoc, this); break; } case (int)swDocumentTypes_e.swDocASSEMBLY: { docHandler = new AssemblyEventHandler(modDoc, this); break; } case (int)swDocumentTypes_e.swDocDRAWING: { docHandler = new DrawingEventHandler(modDoc, this); break; } default: { return false; //Unsupported document type } } docHandler.AttachEventHandlers(); openDocs.Add(modDoc, docHandler); } return true; }
/// <summary> /// Toss out old events and reconnect the Redbrick to the new doc. /// </summary> /// <returns>0. Every time.</returns> int SwApp_ActiveDocChangeNotify() { if (SwApp == null) SwApp = RequestSW(); Document = SwApp.ActiveDoc; if (!(Document.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) && AssySetup) DisconnectAssemblyEvents(); if (!(Document.GetType() == (int)swDocumentTypes_e.swDocPART) && PartSetup) DisconnectPartEvents(); if (!(Document.GetType() == (int)swDocumentTypes_e.swDocDRAWING) && DrawSetup) DisconnectDrawingEvents(); ConnectSelection(); return 0; }
/// <summary> /// Blank out the Redbrick /// </summary> /// <param name="c">A Control object.</param> private void ClearControls(Control c) { foreach (Control item in c.Controls) { c.Controls.Remove(item); item.Dispose(); } Document = (ModelDoc2)_swApp.ActiveDoc; if (Document != null && Document.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY) DisconnectAssemblyEvents(); DisconnectPartEvents(); DisconnectDrawingEvents(); // everything's undone. }