Laservall_solidworks_inject/Extension/SWUtils.cs

4106 lines
150 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Laservall.Solidworks.Model;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swdocumentmgr;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
namespace Laservall.Solidworks.Extension
{
public class SWUtils
{
private const string DEFAULT_CONFIGURATION_ZH = "默认";
private const string DEFAULT_CONFIGURATION_EN = "DEFAULT";
private static String defaultAttiVal = "defaultAttiVal";
private const string filterConfigPreviewCfg = "PreviewCfg";
private const string filterConfigFlexible = "-_flexible";
public static readonly SWUtils util = new SWUtils();
public ISldWorks application = null;
private static bool isSW2015OrLater = false;
private static List<string> toBeClosedFileArray = new List<string>();
private static List<string> openedFileList = new List<string>();
public static Dictionary<string, int> MateMap = new Dictionary<string, int>();
private static System.Data.DataTable previewTable = null;
public static ISldWorks SwApp
{
set
{
util.application = value;
}
get
{
return util.application;
}
}
public static bool IsSW2015OrLater
{
set
{
isSW2015OrLater = value;
}
get
{
return isSW2015OrLater;
}
}
//集成需要取文件属性时自动打开的文件列表,命令结束时自动关闭其中的文件
public static List<String> openFileArray
{
get
{
return toBeClosedFileArray;
}
}
[DllImport("CompoundFileAttribute.dll", CharSet = CharSet.Unicode)]
private extern static bool GetUserdefineProperty(String strPath, String strAttriName, StringBuilder strBuilder);
[DllImport("CompoundFileAttribute.dll", CharSet = CharSet.Unicode)]
private extern static bool SetUserdefineProperty(String strPath, String strAttriName, String strAttriVal, bool bIsWChar);
[DllImport("CompoundFileAttribute.dll", CharSet = CharSet.Unicode)]
private extern static bool GetSummaryProperty(String strPath, int nSummaryId, StringBuilder strBuilder);
[DllImport("CompoundFileAttribute.dll", CharSet = CharSet.Unicode)]
private extern static bool SetSummaryProperty(String strPath, int nSummaryId, String strAttriVal, bool bIsWChar);
private static bool CompoundFileAttributeDllError = false;
/// <summary>
///
/// </summary>
/// <param name="configName"></param>
/// <returns></returns>
public static bool IsConfigNameFiltered(string configName)
{
if (configName.Equals(filterConfigPreviewCfg) || configName.Contains(filterConfigFlexible))
{
return true;
}
return false;
}
/// <summary>
/// 复合文档取自定义属性
/// </summary>
/// <param name="path"></param>
/// <param name="attName"></param>
/// <returns></returns>
[Description("获取自定义属性的值")]
private static String GetAttriVal(String path, String attName)
{
String re = "";
if (CompoundFileAttributeDllError)
{
return re;
}
try
{
StringBuilder strBuilder = new StringBuilder(1024);
GetUserdefineProperty(path, attName, strBuilder);
re = strBuilder.ToString();
}
catch (System.Exception ex)
{
CompoundFileAttributeDllError = true;
//MessageBox.Show("CompoundFileAttribute.dll GetUserdefineProperty:\n" + ex.Message);
}
return re;
}
/// <summary>
/// 复合文档设置SumInfo属性
/// </summary>
/// <param name="path"></param>
/// <param name="attName"></param>
/// <param name="attVal"></param>
/// <returns></returns>
[Description("文档设置属性")]
private static bool SetAttriVal(String path, String attName, String attVal)
{
bool bSuc = false;
if (CompoundFileAttributeDllError)
{
return bSuc;
}
try
{
bool bIsWChar = false;
bSuc = SetUserdefineProperty(path, attName, attVal, bIsWChar);
}
catch (System.Exception ex)
{
CompoundFileAttributeDllError = true;
//MessageBox.Show("CompoundFileAttribute.dll SetUserdefineProperty\n" + ex.Message);
return false;
}
return bSuc;
}
/// <summary>
/// 复合文档获取SumInfo属性
/// </summary>
/// <param name="path"></param>
/// <param name="nSummaryId"></param>
/// <returns></returns>
private static String GetSummaryAttriVal(String path, int nSummaryId)
{
String re = "";
if (CompoundFileAttributeDllError)
{
return re;
}
try
{
StringBuilder strBuilder = new StringBuilder(1024);
GetSummaryProperty(path, nSummaryId, strBuilder);
re = strBuilder.ToString();
}
catch (System.Exception ex)
{
CompoundFileAttributeDllError = true;
//MessageBox.Show("CompoundFileAttribute.dll GetSummaryProperty\n" + ex.Message);
}
return re;
}
/// <summary>
/// 复合文档设置自定义属性
/// </summary>
/// <param name="path"></param>
/// <param name="nSummaryId"></param>
/// <param name="attVal"></param>
/// <returns></returns>
private static bool SetSummaryAttriVal(String path, int nSummaryId, String attVal)
{
bool bSuc = false;
if (CompoundFileAttributeDllError)
{
return bSuc;
}
try
{
bool bIsWChar = false;
bSuc = SetSummaryProperty(path, nSummaryId, attVal, bIsWChar);
}
catch (System.Exception ex)
{
CompoundFileAttributeDllError = true;
//MessageBox.Show("CompoundFileAttribute.dll SetSummaryProperty\n" + ex.Message);
return false;
}
return bSuc;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string CurDocIsTemporaryNew()
{
ModelDoc2 doc = SwApp.ActiveDoc as ModelDoc2;
if (doc != null)
{
string strPath = doc.GetPathName();
if (strPath == "") //temporary file
{
string strTitle = doc.GetTitle();
string strExt = "";
int type = doc.GetType();
switch (type)
{
case (int)swDocumentTypes_e.swDocASSEMBLY:
strExt = ".sldasm";
break;
case (int)swDocumentTypes_e.swDocPART:
strExt = ".sldprt";
break;
case (int)swDocumentTypes_e.swDocDRAWING:
strExt = ".slddrw";
break;
default:
return "";
}
return strTitle + strExt;
}
}
return "";
}
/// <summary>
/// 当前文件是否存在
/// </summary>
/// <returns></returns>
public static bool CurDocIsExist()
{
ModelDoc2 doc = SwApp.ActiveDoc as ModelDoc2;
if (doc != null)
{
return true;
}
return false;
}
public static bool NewUnsaveDocument(string templateFilePath, string otherInfo)
{
ModelDoc2 newDoc = SwApp.NewDocument(templateFilePath, 0, 0, 0) as ModelDoc2;
if (newDoc == null)
{
return false;
}
return true;
}
public static void SetTemplateInfo(string tempalteFilePath, string objFieldInfo)
{
}
/// <summary>
/// 生成预览图
/// </summary>
/// <param name="strFilePath"></param>
/// <param name="strPreviewPath"></param>
/// <returns></returns>
public static bool CreatePreviewFile(string strFilePath, string strPreviewPath)
{
ModelDoc2 actDoc = SwApp.ActiveDoc as ModelDoc2;
//当前文件为空,直接返回
if (actDoc == null)
{
return false;
}
String docName = "";
ModelDoc2 doc = GetDoc(strFilePath);
//在单独窗口中打开的文件不需自动关闭,只需置为当前
bool bNeedClose = false;
if (doc == actDoc)
{
}
else
{
if (doc == null)
{
bNeedClose = true;
}
else
{
if (doc.ActiveView != null)
{
}
else
{
bNeedClose = true;
}
}
OpenDocument(strFilePath, true);
doc = GetDoc(strFilePath);
}
if (doc == null)
{
return false;
}
if (bNeedClose)
{
if (!openFileArray.Contains(strFilePath))
{
openFileArray.Add(strFilePath);
}
}
//全屏缩放
doc.ViewZoomtofit2();
doc.Save();
bool bSucceed = SaveDocumentAs(strFilePath, strPreviewPath);
//当前文件重置
if (actDoc != null)
{
docName = actDoc.GetPathName();
ModelDoc2 curDoc = SwApp.ActiveDoc as ModelDoc2;
if (curDoc != actDoc && !String.IsNullOrEmpty(docName))
{
int errors = 0;
SwApp.ActivateDoc2(docName, false, ref errors);
}
}
return bSucceed;
}
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="strFilePath"></param>
/// <param name="strThumbnailPath"></param>
/// <returns></returns>
[Description("生成缩略图")]
public static bool CreateThumbnailFile(string strFilePath, string strThumbnailPath)
{
//return CreatePreviewFile(strFilePath, strThumbnailPath);
string strThumbnailName = System.IO.Path.GetFileName(strThumbnailPath);
if (string.IsNullOrEmpty(strThumbnailName))
{
return false;
}
int nIndex = strThumbnailPath.LastIndexOf("\\");
if (nIndex == -1)
{
return false;
}
string strTempDir = strThumbnailPath.Substring(0, nIndex);
nIndex = strTempDir.LastIndexOf("\\");
if (nIndex == -1)
{
return false;
}
strTempDir = strTempDir.Substring(0, nIndex);
strTempDir += "\\Preview\\";
string strPreviewPath = strTempDir + strThumbnailName;
if (string.IsNullOrEmpty(strPreviewPath) || !System.IO.File.Exists(strPreviewPath))
{
return false;
}
try
{
System.IO.File.Copy(strPreviewPath, strThumbnailPath, true);
}
catch (System.Exception ex)
{
return false;
}
return true;
}
/// <summary>
/// 装配功能
/// </summary>
/// <param name="parentFilePath">装配文件路径</param>
/// <param name="childFilePath">被装配文件路径</param>
/// <param name="instanceName">被装配文件的配置</param>
/// <returns></returns>
[Description("装配功能")]
public static bool Assemble([Description("父文件路径")] string parentFilePath, [Description("子文件路径")] string childFilePath, [Description("配置名称")] string instanceName, float x, float y, float z)
{
ModelDoc2 doc = GetDoc(parentFilePath);
if (doc == null)
{
return false;
}
AssemblyDoc asm = doc as AssemblyDoc;
if (asm == null)
{
return false;
}
/*ModelDoc2 childDoc = GetDoc(childFilePath);
if (childDoc == null)
{
childDoc = OpenDoc(childFilePath, false);
if (childDoc == null)
{
string strException = Session.MSR.GetString("UI_TEXT_CANNOT_OPEN_FILE");
throw new Exception(strException);
}
}*/
bool ret = true;
/*if (string.IsNullOrEmpty(instanceName))
{
ret = asm.AddComponent(childFilePath, x, y, z);
}
else
{
Component2 comp = asm.AddComponent4(childFilePath, instanceName, x, y, z);
ret = comp != null;
}*/
if (x == 1 && y == 1 && z == 1)
{
Component2 comp = asm.AddComponent4(childFilePath, instanceName, x, y, z);
ret = comp != null;
}
//装配动作在鼠标事件中进行
insertChildFilePath = childFilePath;
insertInstanceName = instanceName;
curAsm = asm;
SwApp.ActivateDoc(parentFilePath);
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
[Description("关闭文档")]
public static bool CloseDocument(string filePath)
{
try
{
SwApp.CloseDoc(filePath);
}
catch (System.Exception ex)
{
return false;
}
return true;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string GetActiveDocument()
{
ModelDoc2 doc = SwApp.ActiveDoc as ModelDoc2;
if (doc != null)
{
return doc.GetPathName();
}
return "";
}
public static ModelDoc2 GetActiveDocument(string path)
{
ModelDoc2 doc = SwApp.GetOpenDocument(path);
if (doc != null)
{
return doc;
}
return null;
return null;
}
public static string GetDataClass(string srtFilePath)
{
ModelDoc2 doc = SwApp.GetOpenDocument(srtFilePath) ?? OpenDocSilently(srtFilePath);
return doc == null ? "" : GetDataClass(doc);
}
private static string GetDataClass(IModelDoc2 tmpDoc)
{
string DataClass = "SolidworksJJJ";
//获取DataClass
if (GetFileType(tmpDoc.GetPathName()) == FileType.Drawing) DataClass = "SolidWorksDRW";
else
{
Configuration configuration = (Configuration)tmpDoc.GetActiveConfiguration();
if (configuration is null) return "";
CustomPropertyManager Cpr = configuration.CustomPropertyManager;
Cpr.Get5("CLASSNAME", true, out string ValOut, out string ResolValOut, out bool WasResolved);
switch (ResolValOut)
{
case "机械机构":
DataClass = "SolidworksJXBCP"; break;
case "半成品(设备)":
DataClass = "SolidworksBCP"; break;
case "机加件":
DataClass = "SolidworksJJJ"; break;
case "参考零件":
DataClass = "SolidworksPART"; break;
case "子装配部件":
DataClass = "SolidworksASM"; break;
case "公司通用标准机构":
DataClass = "SolidworksGSTYSTD"; break;
case "机电公共物料":
DataClass = "SolidworksJDGGWL"; break;
case "电气外购件":
DataClass = "SolidworksDQWGJ"; break;
case "机械外购件":
DataClass = "SolidworksJXWGJ"; break;
case "非生产物料":
DataClass = "SolidworksFSCWL"; break;
case "标准机构":
DataClass = "SolidworksCPSTD"; break;
case "项目":
DataClass = "SolidworksPROJECT"; break;
case "成品":
DataClass = "SolidworksCP";
break;
}
}
return DataClass;
}
#region get cut-list items
// This example shows how to get cut-list items and their custom properties and how to add, modify, and delete a cut-list custom property.
//--------------------------------------------------------------------------
// Preconditions:
// 1. Read the SolidWorks Document Manager API Getting Started topic
// and ensure that the required DLLs have been registered.
// 2. Copy and paste this class into a C# console application in
// Microsoft Visual Studio.
// 3. Ensure that the specified part exists or point to another
// document that contains a cut list with custom properties).
// 4. Add the Solidworks.Interop.swdocumentmgr.dll reference to
// the project:
// a. Right-click the solution in Solution Explorer.
// b. Select Add Reference.
// c. Click the Browse tab.
// d. Load:
// <SolidWorks_install_dir>\api\redist\Solidworks.Interop.swdocumentmgr.dll
// 5. Substitute <your_license_code> with your SolidWorks
// Document Manager license code.
// 6. Compile and run this program in Debug mode.
//
// Postconditions: Inspect the Output Window and the code to see how
// the API is used.
//--------------------------------------------------------------------------
//private void GetWeldmentCutList()
//{
// SwDMClassFactory swClassFact = default(SwDMClassFactory);
// SwDMApplication swDocMgr = default(SwDMApplication);
// SwDMDocument10 swDocument10 = default(SwDMDocument10);
// SwDMDocument13 swDocument13 = default(SwDMDocument13);
// string sDocFileName = null;
// SwDmDocumentType nDocType = default(SwDmDocumentType);
// SwDmDocumentOpenError nRetVal = default(SwDmDocumentOpenError);
// string sLicenseKey = null;
// sLicenseKey = "<your_license_code>";
// // Specify your SolidWorks Document Manager license key
// sDocFileName = ("C:\\Program Files\\SolidWorks Corp\\SolidWorks\\samples\\tutorial\\weldments\\weldment_box2.sldprt");
// // Specify your model document
// nDocType = SwDmDocumentType.swDmDocumentPart;
// swClassFact = new SwDMClassFactory();
// swDocMgr = swClassFact.GetApplication(sLicenseKey) as SwDMApplication;
// swDocument10 = (SwDMDocument10)swDocMgr.GetDocument(sDocFileName, nDocType, false, out nRetVal);
// swDocument13 = (SwDMDocument13)swDocument10;
// Debug.Print("Last Update Stamp: " + swDocument13.GetLastUpdateTimeStamp());
// object[] vCutListItems = null;
// vCutListItems = (object[])swDocument13.GetCutListItems2();
// SwDMCutListItem2 Cutlist = default(SwDMCutListItem2);
// long I = 0;
// SwDmCustomInfoType nType = 0;
// string nLink = null;
// long J = 0;
// object[] vPropNames = null;
// Debug.Print("GET CUT-LIST ITEM");
// for (I = 0; I <= vCutListItems.GetUpperBound(0); I++)
// {
// Cutlist = (SwDMCutListItem2)vCutListItems[I];
// Debug.Print("Name : " + Cutlist.Name);
// Debug.Print(" Quantity : " + Cutlist.Quantity);
// vPropNames = (object[])Cutlist.GetCustomPropertyNames();
// if (!((vPropNames == null)))
// {
// Debug.Print(" GET CUSTOM PROPERTIES");
// for (J = 0; J <= vPropNames.GetUpperBound(0); J++)
// {
// Debug.Print(" Property Name : " + vPropNames[J]);
// Debug.Print(" Property Value : " + Cutlist.GetCustomPropertyValue2((string)vPropNames[J], out nType, out nLink));
// Debug.Print(" Type : " + nType);
// Debug.Print(" Link : " + nLink);
// }
// }
// Debug.Print("_________________________");
// }
// Cutlist = (SwDMCutListItem2)vCutListItems[0];
// Debug.Print("ADD CUSTOM PROPERTY CALLED Testing1");
// Debug.Print(" Custom Property added? " + Cutlist.AddCustomProperty("Testing1", SwDmCustomInfoType.swDmCustomInfoText, "Verify1"));
// Debug.Print(" GET CUSTOM PROPERTIES");
// vPropNames = (object[])Cutlist.GetCustomPropertyNames();
// for (J = 0; J <= vPropNames.GetUpperBound(0); J++)
// {
// Debug.Print(" Property Name : " + vPropNames[J]);
// Debug.Print(" Property Value : " + Cutlist.GetCustomPropertyValue2((string)vPropNames[J], out nType, out nLink));
// Debug.Print(" Type : " + nType);
// Debug.Print(" Link : " + nLink);
// }
// Debug.Print("_________________________");
// Debug.Print("SET NEW CUSTOM PROPERTY VALUE FOR Testing1");
// Debug.Print(" Property Value Before Setting: " + Cutlist.GetCustomPropertyValue2("Testing1", out nType, out nLink));
// Debug.Print(" New Value Set? " + Cutlist.SetCustomProperty("Testing1", "Verify3"));
// Debug.Print(" Property Value After Setting : " + Cutlist.GetCustomPropertyValue2("Testing1", out nType, out nLink));
// Debug.Print(" GET CUSTOM PROPERTIES");
// vPropNames = (object[])Cutlist.GetCustomPropertyNames();
// for (J = 0; J <= vPropNames.GetUpperBound(0); J++)
// {
// Debug.Print(" Property Name : " + vPropNames[J]);
// Debug.Print(" Property Value : " + Cutlist.GetCustomPropertyValue2((string)vPropNames[J], out nType, out nLink));
// Debug.Print(" Type : " + nType);
// Debug.Print(" Link : " + nLink);
// }
// Debug.Print("_________________________");
// Debug.Print("DELETE CUSTOM PROPERTY Testing1");
// Debug.Print(" Delete Property Value? " + Cutlist.DeleteCustomProperty("Testing1"));
// vPropNames = (object[])Cutlist.GetCustomPropertyNames();
// if (!((vPropNames == null)))
// {
// Debug.Print(" GET CUSTOM PROPERTIES");
// for (J = 0; J <= vPropNames.GetUpperBound(0); J++)
// {
// Debug.Print(" Property Name : " + vPropNames[J]);
// Debug.Print(" Property Value : " + Cutlist.GetCustomPropertyValue2((string)vPropNames[J], out nType, out nLink));
// Debug.Print(" Type : " + nType);
// Debug.Print(" Link : " + nLink);
// }
// }
// Debug.Print("_________________________");
// //swDocument10.Save()
// swDocument10.CloseDoc();
//}
#endregion
public static int nInx = 1;
/// <summary>
/// 判断文件是否族表实例
/// </summary>
/// <param name="strFilePath">文件名</param>
/// <param name="strTemplateFilePath">主文件的名称(无主文件时值为空),solidworks族表只有一个物理文件,故strTemplateFilePath = strFilePath</param>
/// <param name="strFamilyTableInstName">族表实例的实例名(即配置名称)</param>
/// <returns>true : 是族表实例, false : 不是</returns>
public static bool IsFamilyTableInstFile(string strFilePath, out string strTemplateFilePath, out string strFamilyTableInstName)
{
strTemplateFilePath = "";
strFamilyTableInstName = "";
//族表隐藏
//return false;
try
{
string strlowPath = strFilePath.ToLower();
if (strlowPath.EndsWith(".slddrw"))
{
return false;
}
ModelDoc2 doc = SwApp.GetOpenDocument(strFilePath);
if (doc == null)
{
doc = OpenDocSilently(strFilePath);
if (doc == null)
{
return false;
}
}
string[] configNames = (string[])doc.GetConfigurationNames();
//string activeConfigurationName = doc.ConfigurationManager.ActiveConfiguration.Name;
if (configNames == null)
{
return false;
}
int len = 0;
foreach (string configName in configNames)
{
if (string.Compare(configName, "Default", true) == 0 || string.Compare(configName, "默认", true) == 0)
strFamilyTableInstName = configName;
//出现 默认<按加工>这类族表,只取最先取到的作为默认配置
else if (len == 0 && (configName.StartsWith("默认") || configName.StartsWith("Default")))
strFamilyTableInstName = configName;
if (IsConfigNameFiltered(configName))
continue;
len++;
}
// 如果没有获取到默认族表,按照激活的配置取
//if (string.IsNullOrWhiteSpace(strFamilyTableInstName))
//{
// strFamilyTableInstName = activeConfigurationName;
//}
/*Configuration config = doc.ConfigurationManager.ActiveConfiguration;
strFamilyTableInstName = config.Name;*/
strTemplateFilePath = strFilePath;
if (len < 2)
{
return false;
}
return true;
}
catch (Exception ex)
{
//Util.LogFile.WriteMessageToLog("IsFamilyTableInstFile ex:" + ex.Message);
return false;
}
}
/// <summary>
/// 获得当前文件的在族表中的实例名称(配置名称)
/// </summary>
/// <param name="strFilePath"></param>
/// <returns></returns>
public static string GetCurFamilyTableInstName(string strFilePath)
{
//族表隐藏
//return "";
//
try
{
string strlowPath = strFilePath.ToLower();
if (strlowPath.EndsWith(".slddrw"))
{
return null;
}
ModelDoc2 doc = SwApp.GetOpenDocument(strFilePath);
if (doc == null)
{
doc = OpenDocSilently(strFilePath);
if (doc == null)
{
return "";
}
}
string[] configNames = (string[])doc.GetConfigurationNames();
if (configNames == null)
{
return "";
}
int len = 0;
foreach (string configName in configNames)
{
if (string.Compare(configName, "Default", true) == 0 || string.Compare(configName, "默认", true) == 0)
return configName;
if (IsConfigNameFiltered(configName))
continue;
len++;
}
if (len < 2)
{
return "";
}
Configuration config = doc.ConfigurationManager.ActiveConfiguration;
return config.Name;
}
catch (Exception ex)
{
//Util.LogFile.WriteMessageToLog("GetCurFamilyTableInstName ex:" + ex.ToString());
return null;
}
}
/// <summary>
/// 获取文件类型
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static FileType GetFileType(string filePath)
{
if (filePath.ToUpper().EndsWith("SLDPRT"))
{
return FileType.Part;
}
else if (filePath.ToUpper().EndsWith("SLDASM"))
{
return FileType.Assembly;
}
else if (filePath.ToUpper().EndsWith("SLDDRW"))
{
return FileType.Drawing;
}
else
{
return FileType.Other;
}
}
/// <summary>
/// 获取文件自定义属性,取其评估值
/// </summary>
/// <param name="filePath"></param>
/// <param name="attributeName"></param>
/// <returns></returns>
public static string GetAttributeValue(string filePath, string attributeName)
{
// 文件名
if (String.Compare(attributeName, "$FileName", true) == 0)
{
String strFileNameWithExt = System.IO.Path.GetFileName(filePath);
int nIndex = strFileNameWithExt.LastIndexOf(".");
if (nIndex == -1)
{
return "";
}
string strFileName = strFileNameWithExt.Substring(0, nIndex);
return strFileName;
}
ModelDoc2 doc = SwApp.GetOpenDocument(filePath);
if (doc == null && IsSW2015OrLater)
{
doc = OpenDocSilently(filePath);
}
if (doc == null) // 文件未打开时的取值方法
{
// 标题
if (string.Compare(attributeName, "SumInfoTitle", true) == 0)
{
return GetSummaryAttriVal(filePath, 2);
}
// 主题
if (string.Compare(attributeName, "SumInfoSubject", true) == 0)
{
return GetSummaryAttriVal(filePath, 3);
}
// 作者
if (string.Compare(attributeName, "SumInfoAuthor", true) == 0)
{
return GetSummaryAttriVal(filePath, 4);
}
// 关键字
if (string.Compare(attributeName, "SumInfoKeywords", true) == 0)
{
return GetSummaryAttriVal(filePath, 5);
}
// 备注
if (string.Compare(attributeName, "SumInfoComment", true) == 0)
{
return GetSummaryAttriVal(filePath, 6);
}
return GetAttriVal(filePath, attributeName);
}
FileType fileType = GetFileType(filePath);
// 内置字段处理只有Part和Assembly有内置字段概念
if (fileType == FileType.Part || fileType == FileType.Assembly)
{
// 只有Part有内置字段MATERIAL
if (fileType == FileType.Part)
{
// 固定属性-材料
if (string.Compare(attributeName, "MATERIAL", true) == 0)
{
string strMat;
GetMaterialPropertyName(filePath, out strMat);
return strMat;
}
}
double dVolume, dArea, dMass;
// 固定属性-体积
if (string.Compare(attributeName, "VOLUME", true) == 0)
{
if (GetVolumeAreaMass(filePath, out dVolume, out dArea, out dMass))
{
return dVolume.ToString("f8");
}
return "";
}
// 固定属性-面积
if (string.Compare(attributeName, "AREA", true) == 0)
{
if (GetVolumeAreaMass(filePath, out dVolume, out dArea, out dMass))
{
return dArea.ToString("f8");
}
return "";
}
// 固定属性-质量
if (string.Compare(attributeName, "MASS", true) == 0)
{
if (GetVolumeAreaMass(filePath, out dVolume, out dArea, out dMass))
{
return dMass.ToString("f8");
}
return "";
}
}
// 标题
if (string.Compare(attributeName, "SumInfoTitle", true) == 0)
{
return doc.get_SummaryInfo((int)swSummInfoField_e.swSumInfoTitle);
}
// 主题
if (string.Compare(attributeName, "SumInfoSubject", true) == 0)
{
return doc.get_SummaryInfo((int)swSummInfoField_e.swSumInfoSubject);
}
// 作者
if (string.Compare(attributeName, "SumInfoAuthor", true) == 0)
{
return doc.get_SummaryInfo((int)swSummInfoField_e.swSumInfoAuthor);
}
// 关键字
if (string.Compare(attributeName, "SumInfoKeywords", true) == 0)
{
return doc.get_SummaryInfo((int)swSummInfoField_e.swSumInfoKeywords);
}
// 备注
if (string.Compare(attributeName, "SumInfoComment", true) == 0)
{
return doc.get_SummaryInfo((int)swSummInfoField_e.swSumInfoComment);
}
try
{
string retValue = doc.GetCustomInfoValue("", attributeName);
return retValue;
}
catch (Exception ex)
{
//Util.LogFile.WriteMessageToLog("GetAttributeValue ex:" + ex.Message);
return null;
}
}
private static Dictionary<string, ModelDoc2> solidWorksDocs;
/*public static void SetsolidWorksDocsBuffer()
{
solidWorksDocs = new Dictionary<string, ModelDoc2>();
SolidEdgeDocument tmpDoc = SEApp.ActiveDocument as SolidEdgeDocument;
string tmpPathLower = tmpDoc.FullName.ToLower();
if (!solidWorksDocs.ContainsKey(tmpPathLower))
{
solidWorksDocs.Add(tmpPathLower, tmpDoc);
}
if (tmpDoc.Type == SolidEdgeFramework.DocumentTypeConstants.igAssemblyDocument)
{
AssemblyDocument asmDoc = tmpDoc as AssemblyDocument;
AddSolidEdgeDocToDic(asmDoc);
}
}
public static void ReleasesolidWorksDocsBuffer()
{
if (solidWorksDocs != null && solidWorksDocs.Count > 0)
{
solidWorksDocs.Clear();
}
}*/
public static void GetIsSuppressed(string assemblyFilePath, ref StringCollection SuppressedList)
{
FileType fileType = GetFileType(assemblyFilePath);
if (fileType != FileType.Assembly)
{
return;
}
ModelDoc2 mdlDoc = GetDoc(assemblyFilePath);
if (mdlDoc == null)
{
mdlDoc = OpenDocSilently(assemblyFilePath);
}
if (mdlDoc == null)
{
return;
}
AssemblyDoc asm = mdlDoc as AssemblyDoc;
//
object[] objs = null;
try
{
objs = (object[])asm.GetComponents(false);
}
catch (Exception ex)
{
//Util.LogFile.WriteMessageToLog(assemblyFilePath + "GetComponents ex:" + ex.Message);
}
if (objs == null)
{
return;
}
int len = objs.Length;
for (int i = 0; i < len; i++)
{
IComponent2 comp = objs[i] as IComponent2;
if (comp != null)
{
swComponentSuppressionState_e suppresionState = (swComponentSuppressionState_e)comp.GetSuppression();
string partID = Path.GetFileNameWithoutExtension(comp.GetPathName());
if (suppresionState == swComponentSuppressionState_e.swComponentSuppressed)
{
Debug.Print(comp.GetPathName());
SuppressedList.Add(partID);
}
}
}
}
/// <summary>
/// 获取文件装配结构
/// </summary>
/// <param name="assemblyFilePath"></param>
/// <returns></returns>
//public static CADStructure GetAssemblyChildren(string assemblyFilePath)
//{
// CADStructure cadStructure = new CADStructureImpl();
// try
// {
// SwDMClassFactory swCf;
// swCf = new SwDMClassFactory();
// SwDMApplication swDocMgr;
// swDocMgr = (SwDMApplication)swCf.GetApplication(sLicenseKey);
// SwDMDocument12 swDoc12;
// SwDmDocumentOpenError res;
// SwDmDocumentType dt;
// dt = SwDmDocumentType.swDmDocumentAssembly;
// if (!assemblyFilePath.ToUpper().EndsWith("SLDASM"))
// {
// return cadStructure;
// }
// swDoc12 = swDocMgr.GetDocument(assemblyFilePath, dt, true, out res) as SwDMDocument12;
// if (swDoc12 == null | (res != SwDmDocumentOpenError.swDmDocumentOpenErrorNone))
// {
// return cadStructure;
// }
// Debug.Print("Getting the active configuration...");
// SwDMConfiguration8 activeConfig;
// SwDMConfigurationMgr configMgr;
// configMgr = swDoc12.ConfigurationManager;
// configMgr.GetConfigurationNames();
// activeConfig = configMgr.GetConfigurationByName(configMgr.GetActiveConfigurationName()) as SwDMConfiguration8;
// if (activeConfig == null)
// {
// Debug.Print("Error getting the active configuration...");
// return cadStructure;
// }
// Debug.Print("Getting the components of the active configuration...");
// object[] vComponents;
// vComponents = (object[])activeConfig.GetComponents();
// SwDMComponent6 swDmComponent;
// int i;
// for (i = 0; i < vComponents.Length; i++)
// {
// swDmComponent = (SwDMComponent6)vComponents[i];
// string compPathName = swDmComponent.PathName;
// if (swDmComponent.IsVirtual)
// {
// return cadStructure;
// }
// if (!File.Exists(compPathName))
// {
// compPathName=Path.GetDirectoryName(assemblyFilePath) +"\\"+ Path.GetFileName(compPathName);
// }
// CADStructureItem tmpItem = null;
// string configName = swDmComponent.ConfigurationName;
// {
// tmpItem = new CADStructureItemImpl(compPathName, configName);
// }
// tmpItem.RelatedBOM = true;
// cadStructure.AddItem(tmpItem, true);
// }
// return cadStructure;
// }
// catch (Exception ee)
// {
// throw ee;
// }
//}
public static bool SetAllPartResolved(string assemblyFilePath)
{
try
{
ModelDoc2 modelDoc = GetDoc(assemblyFilePath);
if (modelDoc.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)
{
return false;
}
AssemblyDoc assemblyDoc = modelDoc as AssemblyDoc;
return assemblyDoc.ResolveAllLightweight();
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 获取模型图对应的工程图
/// </summary>
/// <param name="modelFilePath"></param>
/// <returns></returns>
public static StringBuilder GetDrawingFileNameFromModel(string modelFilePath)
{
StringBuilder arr = new StringBuilder();
try
{
String upper = modelFilePath.ToUpper();
if (!upper.EndsWith(".SLDPRT") && !upper.EndsWith(".SLDASM"))
{
return arr;
}
//ModelDoc2 doc = GetDoc(modelFilePath);
//if (doc == null)
//{
// return arr;
//}
string path = modelFilePath.Substring(0, modelFilePath.Length - 6);
path += "SLDDRW";
if (System.IO.File.Exists(path))
{
arr.AppendLine(path);
}
// return arr;
ModelDoc2 doc = GetDoc(modelFilePath);
if (doc == null)
{
doc = OpenDocSilently(modelFilePath);
if (doc == null)
{
return arr;
}
}
string[] configNames = (string[])doc.GetConfigurationNames();
if (configNames == null)
{
return arr;
}
foreach (string configName in configNames)
{
if (IsConfigNameFiltered(configName))
continue;
Configuration tmpConfig = doc.GetConfigurationByName(configName) as Configuration;
try
{
path = Path.Combine(Path.GetDirectoryName(modelFilePath), tmpConfig.Name + ".slddrw");
}
catch (Exception)
{
continue;
}
if (File.Exists(path))
{
arr.AppendLine(path);
}
}
}
catch (Exception ex)
{
//Util.LogFile.WriteMessageToLog("GetDrawingFileNameFromModel ex:" + ex.Message);
}
//String modleFileName = System.IO.Path.GetFileName(modelFilePath);
//String dir = System.IO.Path.GetDirectoryName(modelFilePath);
//String strSection = "relation";
//String strTimeSection = "savetime";
////strPath为记录2D-3D关系的文件
//String strPath = dir + "\\" + "relation.ini";
//int nSize = 256;
//Type type = Type.GetTypeFromProgID("DynaTeam.Util.FilesInPathImpl");
//FilesInPath filesInPath = Activator.CreateInstance(type) as FilesInPath;
//type = Type.GetTypeFromProgID("DynaTeam.Util.InitialFileImpl");
//InitialFile initFile = Activator.CreateInstance(type) as InitialFile;
//type = Type.GetTypeFromProgID("DynaTeam.Util.FileLastTimeImpl");
//FileLastTime fwlTime = Activator.CreateInstance(type) as FileLastTime;
////取目录下的所有工程图文件所对应的3D图纸
//StringArray files = filesInPath.GetFilesInPath(dir, ".slddrw");
//int nFileCount = files.Count;
//for (int i = 0; i < nFileCount; i++)
//{
// String tmpFile = files.GetAt(i);
// if (String.IsNullOrEmpty(tmpFile))
// {
// continue;
// }
// String strKey = System.IO.Path.GetFileName(tmpFile);
// String strRe = initFile.ReadValue(strSection, strKey, strPath, nSize);
// if (!String.IsNullOrEmpty(strRe))
// {
// //判断文件名是否相同
// if (String.Compare(strRe, modleFileName, true) == 0)
// {
// String strFileLwTime = fwlTime.GetFileLastWriteTime(tmpFile);
// String strFlwTime = initFile.ReadValue(strTimeSection, strKey, strPath, nSize);
// //判断记录时间和文件时间是否一致
// if (String.Compare(strFileLwTime, strFlwTime, true) == 0)
// {
// arr.Add(tmpFile);
// continue;
// }
// }
// else
// {
// continue;
// }
// }
// //获取工程图对应模型图
// strRe = GetModelFileNameFromDrawing(tmpFile);
// if (!String.IsNullOrEmpty(strRe))
// {
// String strValue = System.IO.Path.GetFileName(strRe);
// initFile.WriteValue(strSection, strKey, strPath, strValue);
// String strFileLwTime = fwlTime.GetFileLastWriteTime(tmpFile);
// initFile.WriteValue(strTimeSection, strKey, strPath, strFileLwTime);
// if (String.Compare(strValue, modleFileName, true) == 0)
// {
// arr.Add(tmpFile);
// }
// }
//}
return arr;
}
/// <summary>
/// 获取工程图对应模型图
/// </summary>
/// <param name="drawingFilePath"></param>
/// <returns></returns>
public static string GetModelFileNameFromDrawing(string drawingFilePath)
{
if (System.IO.Path.GetExtension(drawingFilePath).ToUpper() != ".SLDDRW")
{
return "";
}
string path = drawingFilePath.Substring(0, drawingFilePath.Length - 6);
string prtPath = path + "SLDPRT";
string asmPath = path + "SLDASM";
//string prtPath = path + "sldprt";
//string asmPath = path + "sldasm";
string modelPath = "";
if (System.IO.File.Exists(prtPath))
{
modelPath = prtPath;
}
else if (System.IO.File.Exists(asmPath))
{
modelPath = asmPath;
}
else
{
ModelDoc2 mdlDoc = GetDoc(drawingFilePath);
//if (mdlDoc == null)
//{
// try
// {
// mdlDoc = OpenDoc(drawingFilePath, false);
// }
// catch (System.Exception ex)
// {
// return modelPath;
// }
//}
if (mdlDoc != null)
{
// Return Value : objs
// Array of strings; there are two strings for each document returned in this list of dependent files:
// first string is the file name
// second string is the filename with the complete pathname
object[] objs = mdlDoc.GetDependencies2(false, true, false) as object[];
if (objs != null)
{
int nLength = objs.Length;
for (int i = 0; i < nLength; i++)
{
++i;
if (i < nLength)
{
String strDependence = objs[i] as String;
if (!String.IsNullOrEmpty(strDependence) && System.IO.File.Exists(strDependence)
&& System.IO.Path.GetExtension(strDependence).ToUpper() != ".SLDDRW")
{
return strDependence;
}
}
}
}
}
}
return modelPath;
}
/// <summary>
/// 打开文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="bActivce">是否激活文件窗口</param>
/// <returns></returns>
public static bool OpenDocument(string path, bool bActivce, bool refreshDraw = false)
{
if (bActivce) //将path从列表中去除
{
if (openFileArray.Contains(path))
{
openFileArray.Remove(path);
}
}
ModelDoc2 actDoc = SwApp.ActiveDoc as ModelDoc2;
ModelDoc2 doc = GetDoc(path);
if (doc != null)
{
if (bActivce)
{
doc.Visible = true;
SwApp.ActivateDoc(path);
//if (!openFileArray.Contains(path) && doc != actDoc)
//{
// openFileArray.Add(path);
//}
if (refreshDraw)
{
// 2024-06-17 部分工程师出现派生后图纸内容没变化的情况,所以在打开图纸时增加刷新
if (doc.GetType() == (int)swDocumentTypes_e.swDocDRAWING)
{
var docExt = doc.Extension;
docExt.Rebuild((int)swRebuildOptions_e.swCurrentSheetDisp);
}
}
}
return true;
}
else
{
doc = OpenDoc(path, bActivce);
return (doc != null);
}
}
/// <summary>
/// 保存文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool SaveDocument(string filePath)
{
try
{
ModelDoc2 doc = GetDoc(filePath);
if (doc == null)
{
return false;
}
//int swErrors = -1;
//int swWarnings = -1;
//return doc.Save3(1, ref swErrors, ref swWarnings);
//SAVE3会不灵存不到文件
doc.Save();
return true;
}
catch (Exception ee)
{
throw ee;
}
//doc.Save();
//return true;
}
/// <summary>
/// 另存文件,可以另存为不同格式的文件(.jpg,.pdf,.iges...等)
/// </summary>
/// <param name="filePath"></param>
/// <param name="newFilePath"></param>
/// <returns></returns>
public static bool SaveDocumentAs(string filePath, string newFilePath)
{
try
{
if (filePath == null)
{
ModelDoc2 doc2 = SwApp.ActiveDoc as ModelDoc2;
if (doc2 != null && doc2.GetPathName() == "")
{
return doc2.SaveAs(newFilePath);
}
else
{
return false;
}
}
ModelDoc2 doc = GetDoc(filePath);
if (doc == null)
{
return false;
}
return doc.SaveAs(newFilePath);
}
catch (Exception ee)
{
throw ee;
}
}
// To export one or more drawing sheets to PDF:
// 1. Get the IExportPdfData object using ISldWorks::GetExportFileData.
// 2. Set the sheets to export to PDF using IExportPdfData::SetSheets.
// 3. Save the sheets using IModelDocExtension::SaveAs.
// To export a part or assembly to 3D PDF:
// 1. Get the IExportPdfData object using ISldWorks::GetExportFileData.
// 2. Set IExportPdfData::ExportAs3D to true.
// 3. Save the part or assembly using IModelDocExtension::SaveAs.
public static bool ExportFile2Pdf3D(string filePath, string newFilePath)
{
if (!newFilePath.EndsWith(".pdf"))
{
return false;
}
bool bIsDrw = filePath.EndsWith(".slddrw");
IModelDoc2 mdlDoc = OpenDoc(filePath, true);
if (mdlDoc == null)
{
return false;
}
bool bSuc = false;
// 工程图3d效果无意义普通处理
if (!bIsDrw)
{
ExportPdfData swExportPDFData = default(ExportPdfData);
swExportPDFData = (ExportPdfData)SwApp.GetExportFileData((int)swExportDataFileType_e.swExportPdfData);
swExportPDFData.ExportAs3D = true;
IModelDocExtension ex = mdlDoc.Extension;
int errors = 0;
int warnings = 0;
bSuc = ex.SaveAs(newFilePath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, swExportPDFData, ref errors, ref warnings);
}
else
{
bSuc = mdlDoc.SaveAs(newFilePath);
}
return bSuc;
}
/// <summary>
/// 设置文件属性
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="attributeName">属性名</param>
/// <param name="attributeValue">属性值</param>
/// <returns></returns>
public static bool SetAttributeValue(string filePath, string attributeName, string attributeValue)
{
FileType fileType = GetFileType(filePath);
//内置字段处理只有Part和Assembly有内置字段概念
if (fileType == FileType.Part || fileType == FileType.Assembly)
{
//只有Part有内置字段MATERIAL
if (fileType == FileType.Part)
{
//固定属性-材料
if (string.Compare(attributeName, "MATERIAL", true) == 0)
{
return false;
}
}
//固定属性-体积
if (string.Compare(attributeName, "VOLUME", true) == 0)
{
return false;
}
//固定属性-面积
if (string.Compare(attributeName, "AREA", true) == 0)
{
return false;
}
//固定属性-质量
if (string.Compare(attributeName, "MASS", true) == 0)
{
return false;
}
}
ModelDoc2 doc = SwApp.GetOpenDocument(filePath);
if (doc == null && IsSW2015OrLater)
{
doc = OpenDocSilently(filePath);
}
if (doc == null)
{
// 标题
if (string.Compare(attributeName, "SumInfoTitle", true) == 0)
{
return SetSummaryAttriVal(filePath, 2, attributeValue);
}
// 主题
if (string.Compare(attributeName, "SumInfoSubject", true) == 0)
{
return SetSummaryAttriVal(filePath, 3, attributeValue);
}
// 作者
if (string.Compare(attributeName, "SumInfoAuthor", true) == 0)
{
return SetSummaryAttriVal(filePath, 4, attributeValue);
}
// 关键字
if (string.Compare(attributeName, "SumInfoKeywords", true) == 0)
{
return SetSummaryAttriVal(filePath, 5, attributeValue);
}
// 备注
if (string.Compare(attributeName, "SumInfoComment", true) == 0)
{
return SetSummaryAttriVal(filePath, 6, attributeValue);
}
return SetAttriVal(filePath, attributeName, attributeValue);
}
try
{
// 标题
if (string.Compare(attributeName, "SumInfoTitle", true) == 0)
{
doc.set_SummaryInfo((int)swSummInfoField_e.swSumInfoTitle, attributeValue);
}
// 主题
else if (string.Compare(attributeName, "SumInfoSubject", true) == 0)
{
doc.set_SummaryInfo((int)swSummInfoField_e.swSumInfoSubject, attributeValue);
}
// 作者
else if (string.Compare(attributeName, "SumInfoAuthor", true) == 0)
{
doc.set_SummaryInfo((int)swSummInfoField_e.swSumInfoAuthor, attributeValue);
}
// 关键字
else if (string.Compare(attributeName, "SumInfoKeywords", true) == 0)
{
doc.set_SummaryInfo((int)swSummInfoField_e.swSumInfoKeywords, attributeValue);
}
// 备注
else if (string.Compare(attributeName, "SumInfoComment", true) == 0)
{
doc.set_SummaryInfo((int)swSummInfoField_e.swSumInfoComment, attributeValue);
}
else
{
if (IsAttributeExist(doc, attributeName))
{
doc.set_CustomInfo2("", attributeName, attributeValue);
}
else
{
doc.AddCustomInfo3("", attributeName, (int)swCustomInfoType_e.swCustomInfoText, attributeValue);
}
}
}
catch (Exception e)
{
String errMsg = "SetProperty '" + attributeName + ", error: " + e.Message + ".";
//MessageBox.Show(errMsg);
}
return true;
}
/// <summary>
/// 文件是否加载
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool IsFileOpen(string path)
{
ModelDoc2 doc = GetDoc(path);
if (doc == null)
{
return false;
}
else
{
return true;
}
}
/// <summary>
///
/// </summary>
/// <param name="templateFilePath"></param>
/// <param name="fileDir"></param>
/// <param name="fileNameWithoutExt"></param>
/// <returns></returns>
public static string NewDocumnet(string templateFilePath, string fileDir, string fileNameWithoutExt)
{
ModelDoc2 newDoc = SwApp.NewDocument(templateFilePath, 0, 0, 0) as ModelDoc2;
if (newDoc == null)
{
return "";
}
string fileExt = ".sldprt";
if (newDoc.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
{
fileExt = ".sldasm";
}
else if (newDoc.GetType() == (int)swDocumentTypes_e.swDocDRAWING)
{
fileExt = ".slddrw";
}
ModelDocExtension swModExt = default(ModelDocExtension);
swModExt = newDoc.Extension;
if (fileNameWithoutExt == null || fileNameWithoutExt == "")
{
newDoc.Save();
return newDoc.GetPathName();
}
else
{
string fileFullPath = fileDir + fileNameWithoutExt + fileExt;
int errors = 0;
int warnings = 0;
if (swModExt.SaveAs(fileFullPath, 0, 0, 0, ref errors, ref warnings))
{
return fileFullPath;
}
else
{
return newDoc.GetPathName();
}
}
}
private static IComponent2 selectedComp = null;
public static string GetSelectModelPath()
{
string selectedModelPath = "";
string selectedModelPathParent = "";
IModelDoc2 doc = SwApp.ActiveDoc as IModelDoc2;
ISelectionMgr selMgr = doc.SelectionManager as ISelectionMgr;
if (selMgr != null)
{
int iMark = 0;
int nSelObjCout = selMgr.GetSelectedObjectCount2(iMark);
if (nSelObjCout > 1)
throw new Exception("当前选中多个模型,请选择单个模型");
else if (nSelObjCout == 0)
return selectedModelPath;
IComponent2 comp = selMgr.GetSelectedObjectsComponent4(1, iMark) as IComponent2;
if (comp != null)
{
selectedComp = comp;
selectedModelPath = comp.GetPathName();
IComponent2 parentComp = comp.GetParent();
if (parentComp != null)
selectedModelPathParent = parentComp.GetPathName();
}
}
return selectedModelPath + "|" + selectedModelPathParent;
}
/// <summary>
/// 激活装配下选中的单个零件,若选中多个,则不激活
/// </summary>
/// <returns></returns>
public static bool ActiveSelectPart()
{
IModelDoc2 doc = SwApp.ActiveDoc as IModelDoc2;
if (doc.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
{
ISelectionMgr selMgr = doc.SelectionManager as ISelectionMgr;
if (selMgr != null)
{
int iMark = 0;
IComponent2 compObj = null;
int nSelObjCout = selMgr.GetSelectedObjectCount2(iMark);
for (int i = 1; i <= nSelObjCout; i++)
{
IComponent2 comp = selMgr.GetSelectedObject6(i, iMark) as IComponent2;
if (compObj == null)
{
compObj = comp;
}
else
{
//选中了多个对象
return false;
}
}
if (compObj != null)
{
//active selected object
ModelDoc2 tmpDoc = compObj.GetModelDoc() as ModelDoc2;
if (tmpDoc != null && tmpDoc != doc)
{
int errors = 0;
SwApp.ActivateDoc2(tmpDoc.GetPathName(), false, ref errors);
if (errors == 0)
{
ModelDoc2 activeDoc = SwApp.ActiveDoc as ModelDoc2;
if (tmpDoc == activeDoc || String.Compare(activeDoc.GetPathName(), tmpDoc.GetPathName(), true) == 0)
{
return true;
}
}
}
}
}
}
return false;
}
/// <summary>
/// 关闭自动打开的文档
/// </summary>
public static void CloseOpenedDoc()
{
foreach (String fileName in openFileArray)
{
if (!String.IsNullOrEmpty(fileName))
{
CloseDocument(fileName);
}
}
openFileArray.Clear();
}
/// <summary>
/// 清理自动打开文档列表
/// </summary>
public static void ClearOpenedDocList()
{
openFileArray.Clear();
}
/// <summary>
/// 获取文件所引用的其他文件
/// </summary>
/// <param name="strPartPath"></param>
/// <returns></returns>
public static StringBuilder GetPartReferences(string strPartPath)
{
return SWUtils.GetPartDependencies(strPartPath);
}
/// <summary>
/// 同步工程图属性(from model file that has the same name)
/// </summary>
///
public static void SyncDrawProp()
{
ModelDoc2 doc = SwApp.ActiveDoc as ModelDoc2;
if (doc != null)
{
String fileName = doc.GetPathName();
StringBuilder strArray = GetDrawingFileNameFromModel(fileName);
if (strArray == null || strArray.Length != 1)
{
return;
}
var drwFileName = strArray.ToString().Split('\n')[0];
ModelDoc2 drwDoc = GetDoc(drwFileName);
if (drwDoc == null)
{
drwDoc = OpenDoc(drwFileName, false);
if (drwDoc == null)
{
return;
}
}
object[] propNames = doc.GetCustomInfoNames2("") as object[];
if (propNames == null)
{
return;
}
int len = propNames.Length;
for (int i = 0; i < len; i++)
{
String propName = propNames[i] as String;
if (!String.IsNullOrEmpty(propName))
{
String res = doc.GetCustomInfoValue("", propName);
bool bSuc = SetAttributeValue(drwFileName, propName, res);
}
}
//保存工程图
drwDoc.Save();
}
}
#region private function
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static ModelDoc2 GetDoc(string path)
{
ModelDoc2 doc = SwApp.GetOpenDocument(path);
if (doc != null)
{
return doc;
}
else if (path.ToLower().EndsWith("dot"))
{
return OpenDocSilently(path);
}
return null;
}
/// <summary>
/// 打开文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="visible">是否显示</param>
/// <returns></returns>
private static ModelDoc2 OpenDoc(string path, bool visible)
{
//释放内存
MemoryMonitor();
swDocumentTypes_e type = swDocumentTypes_e.swDocNONE;
string ext = System.IO.Path.GetExtension(path).ToUpper().Substring(1);
if (ext == "SLDASM")
{
type = swDocumentTypes_e.swDocASSEMBLY;
}
else if (ext == "SLDPRT")
{
type = swDocumentTypes_e.swDocPART;
}
else if (ext == "SLDDRW")
{
type = swDocumentTypes_e.swDocDRAWING;
}
else
{
return null;
}
int err = 0;
int war = 0;
swOpenDocOptions_e options = swOpenDocOptions_e.swOpenDocOptions_Silent | swOpenDocOptions_e.swOpenDocOptions_LoadLightweight;
ModelDoc2 doc = SwApp.OpenDoc6(path, (int)type, (int)options, "", ref err, ref war);
if (doc != null)
{
doc.Visible = visible;
}
if (!visible)
{
if (!openFileArray.Contains(path))
{
openFileArray.Add(path);
}
}
return doc;
}
/// <summary>
/// 静默的打开文件
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public static ModelDoc2 OpenDocSilently(string path)
{
if (solidWorksDocs != null)
{
if (solidWorksDocs.ContainsKey(path))
{
return solidWorksDocs[path];
}
}
//释放内存
//MemoryMonitor();
swDocumentTypes_e type = swDocumentTypes_e.swDocNONE;
string ext = System.IO.Path.GetExtension(path).ToUpper().Substring(1);
if (ext == "SLDASM" || ext == "ASMDOT")
{
type = swDocumentTypes_e.swDocASSEMBLY;
}
else if (ext == "SLDPRT" || ext == "PRTDOT")
{
type = swDocumentTypes_e.swDocPART;
}
else if (ext == "SLDDRW" || ext == "DRWDOT")
{
type = swDocumentTypes_e.swDocDRAWING;
}
else
{
return null;
}
int err = 0;
int war = 0;
swOpenDocOptions_e options = swOpenDocOptions_e.swOpenDocOptions_Silent | swOpenDocOptions_e.swOpenDocOptions_LoadLightweight;
SwApp.DocumentVisible(false, (int)type);
ModelDoc2 doc = SwApp.OpenDoc6(path, (int)type, (int)options, "", ref err, ref war);
SwApp.DocumentVisible(true, (int)type);
if (!openFileArray.Contains(path))
{
openFileArray.Add(path);
}
return doc;
}
public static bool ClearAttribute(string modelPath)
{
object PropNames = null;
object PropTypes = null;
object PropValues = null;
object Resolved = null;
ModelDoc2 modelDoc2 = GetDoc(modelPath) ?? OpenDocSilently(modelPath);
if (modelDoc2 != null)
{
Configuration configuration = (Configuration)modelDoc2.GetActiveConfiguration();
CustomPropertyManager Cpr = configuration.CustomPropertyManager;
int count = Cpr.GetAll2(ref PropNames, ref PropTypes, ref PropValues, ref Resolved);
if (count.Equals(0))
{
return false;
}
foreach (string PropName in (object[])PropNames)
{
if (PropName != "名称")
{
Cpr.Delete2(PropName);
}
}
return true;
}
return false;
}
public static string[] GetConfigData(string CADPath, string[] ConfigNames)
{
string[] ConfigData = new string[ConfigNames.Length];
if (CADPath.ToLower().EndsWith(".slddrw"))
{
return null;
}
ModelDoc2 doc = SwApp.GetOpenDocument(CADPath);
if (doc == null)
{
doc = OpenDocSilently(CADPath);
if (doc == null)
{
return null;
}
}
Configuration config = doc.ConfigurationManager.ActiveConfiguration;
if (config == null)
{
return null;
}
CustomPropertyManager Cpr = config.CustomPropertyManager;
for (int i = 0; i < ConfigNames.Length; i++)
{
Cpr.Get5(ConfigNames[i], true, out string ValOut, out string ResolValOut, out bool WasResolved);
ConfigData[i] = ResolValOut;
}
return ConfigData;
}
public static bool AddAttribute(string modelPath)
{
ModelDoc2 modelDoc2 = GetDoc(modelPath) ?? OpenDocSilently(modelPath);
if (modelDoc2 != null)
{
Configuration configuration = (Configuration)modelDoc2.GetActiveConfiguration();
CustomPropertyManager Cpr = configuration.CustomPropertyManager;
Cpr.Add3("图号", (int)swCustomInfoType_e.swCustomInfoText, "$PRP:\"SW-File Name\"", 2);
Cpr.Add3("单位", (int)swCustomInfoType_e.swCustomInfoText, "台", 2);
Cpr.Add3("CLASSNAME", (int)swCustomInfoType_e.swCustomInfoText, "参考零件", 2);
Cpr.Set2("CLASSNAME", "参考零件");
return true;
}
return false;
}
public static bool AddAttribute(string modelPath, string configName, string configValue, swCustomInfoType_e infoType)
{
ModelDoc2 modelDoc2 = GetDoc(modelPath) ?? OpenDocSilently(modelPath);
if (modelDoc2 != null)
{
Configuration configuration = (Configuration)modelDoc2.GetActiveConfiguration();
CustomPropertyManager Cpr = configuration.CustomPropertyManager;
Cpr.Add3(configName, (int)infoType, configValue, 1);
return true;
}
return false;
}
/// <summary>
/// 获取文件的材料名sw只有partDoc才有材料属性
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static bool GetMaterialPropertyName(string filePath, out string strMaterialName)
{
strMaterialName = "";
ModelDoc2 doc = GetDoc(filePath);
if (doc == null)
{
return false;
}
PartDoc partDoc = doc as PartDoc;
if (partDoc == null)
{
return false;
}
Configuration config = doc.ConfigurationManager.ActiveConfiguration;
string strDataBase;
strMaterialName = partDoc.GetMaterialPropertyName2(config.Name, out strDataBase);
return true;
}
/// <summary>
/// 获取文件的内置属性(文件内部计算得出)
/// </summary>
/// <param name="dVolume">体积 m^3</param>
/// <param name="dArea">面积 m^2</param>
/// <param name="dMass">质量 kg</param>
private static bool GetVolumeAreaMass(string filePath, out double dVolume, out double dArea, out double dMass)
{
dVolume = 0.0;
dArea = 0.0;
dMass = 0.0;
ModelDoc2 doc = GetDoc(filePath);
if (doc == null)
{
return false;
}
ModelDocExtension docExt = doc.Extension;
int status = 0;
/// The return value is a 0-based array of doubles as follows:
/// [ CenterOfMassX, CenterOfMassY, CenterOfMassZ, Volume, Area, Mass,
/// MomXX, MomYY, MomZZ, MomXY, MomZX, MomYZ, Accuracy ]
double[] objs = docExt.GetMassProperties(1, ref status) as double[];
if (status == (int)swMassPropertiesStatus_e.swMassPropertiesStatus_OK)
{
dVolume = (double)objs[3];
dArea = (double)objs[4];
dMass = (double)objs[5];
return true;
}
return false;
}
private static bool IsStringSame(String val)
{
return String.Compare(val, defaultAttiVal, true) == 0;
}
/// <summary>
/// 获得零件引用的零件图纸
/// </summary>
/// <param name="fileName">需要查找引用关系的文件</param>
/// <returns> 引用零件的文件名array</returns>
private static StringBuilder GetPartDependencies(String fileName)
{
StringBuilder arr = new StringBuilder();
#region
//if (!fileName.ToUpper().EndsWith("SLDPRT"))
//{
// string drawingPath = fileName.Substring(0, fileName.Length - 7) + ".slddrw";
// if (File.Exists(drawingPath))
// {
// arr.Add(drawingPath);
// }
//}
//return arr;
#endregion
ModelDoc2 mdlDoc = GetDoc(fileName);
if (mdlDoc != null)
{
int nType = mdlDoc.GetType();
if (nType != (int)swDocumentTypes_e.swDocPART)
{
return arr;
}
IModelDoc2 modelDoc2 = (IModelDoc2)mdlDoc;
object[] objs = modelDoc2.GetDependencies(1, 0) as object[];
// object[] objs = mdlDoc.GetDependencies2(true, true, false) as object[];
//Return Value : objs
//Array of strings; there are two strings for each document returned in this list of dependent files:
//first string is the file name
//second string is the filename with the complete pathname
if (objs != null)
{
int nLength = objs.Length;
for (int i = 0; i < nLength; i++)
{
++i;
if (i < nLength)
{
String strDependence = objs[i] as String;
if (!String.IsNullOrEmpty(strDependence) && strDependence.ToLower().EndsWith(".sldprt"))
{
if (String.Compare(fileName, strDependence, true) == 0)
{
//引用了自己的镜像,防止死循环
continue;
}
arr.AppendLine(strDependence);
}
}
}
}
}
return arr;
}
/// <summary>
/// 监控内存自动关闭文件以释放内存
/// </summary>
/// <returns></returns>
private static bool MemoryMonitor()
{
//bLimited为true表示内存超出控制范围
bool bLimited = false;
try
{
System.Diagnostics.Process pro = System.Diagnostics.Process.GetCurrentProcess();
long lWorkingSet = pro.WorkingSet64;
long lPagedMemory = pro.PagedMemorySize64;
long lLimited = (long)(1024 * 1024 * 1024 * 0.8);
bLimited = lWorkingSet > lLimited || lPagedMemory > lLimited;
int nCount = openFileArray.Count;
//关闭集成打开的文件释放内存
if (bLimited)
{
while (nCount > 0)
{
string strName = openFileArray[0];
openFileArray.RemoveAt(0);
CloseDocument(strName);
lWorkingSet = pro.WorkingSet64;
lPagedMemory = pro.PagedMemorySize64;
bLimited = lWorkingSet > lLimited || lPagedMemory > lLimited;
if (!bLimited)
{
return !bLimited;
}
nCount--;
}
}
//lWorkingSet = pro.WorkingSet64;
//lPagedMemory = pro.PagedMemorySize64;
//bLimited = lWorkingSet > lLimited || lPagedMemory > lLimited;
////若内存依然不足关闭sld打开的文件释放内存
//if (bLimited)
//{
// List<string> fileList = SwAddin.filesInSession;
// nCount = fileList.Count;
// while (nCount > 0)
// {
// string strName = fileList[0];
// fileList.RemoveAt(0);
// CloseDocument(strName);
// lWorkingSet = pro.WorkingSet64;
// lPagedMemory = pro.PagedMemorySize64;
// bLimited = lWorkingSet > lLimited || lPagedMemory > lLimited;
// if (!bLimited)
// {
// return !bLimited;
// }
// nCount--;
// }
//}
//若内存依然不足轻量化sl装配下的文件释放内存
//String asmFile = SwAddin.topAsmFile;
//if (!String.IsNullOrEmpty(SwAddin.topAsmFile))
//{
// ModelDoc2 mdlDoc = GetDoc(asmFile);
// if (mdlDoc == null)
// {
// return !bLimited;
// }
// AssemblyDoc asm = mdlDoc as AssemblyDoc;
// if (asm == null)
// {
// return !bLimited;
// }
// object[] objs = (object[])asm.GetComponents(true);
// if (objs == null)
// {
// return !bLimited;
// }
// int len = objs.Length;
// for (int i = 0; i < len; i++)
// {
// IComponent2 comp = objs[i] as IComponent2;
// if (comp != null)
// {
// bool bIsSuppressed = comp.IsSuppressed();
// if (!bIsSuppressed)
// {
// comp.SetSuppression2((int)swComponentSuppressionState_e.swComponentFullyLightweight);
// }
// lWorkingSet = pro.WorkingSet64;
// lPagedMemory = pro.PagedMemorySize64;
// bLimited = lWorkingSet > lLimited || lPagedMemory > lLimited;
// if (!bLimited)
// {
// return !bLimited;
// }
// }
// }
//}
}
catch (System.Exception ex)
{
}
return !bLimited;
}
/// <summary>
/// 判断文件中是否存在该属性
/// </summary>
/// <param name="doc"></param>
/// <param name="strAttriName"></param>
/// <returns></returns>
private static bool IsAttributeExist(IModelDoc2 doc, String strAttriName)
{
if (doc == null)
{
return false;
}
var cfgMgr = doc.ConfigurationManager;
var cpMgr = cfgMgr.ActiveConfiguration.CustomPropertyManager;
object objs = cpMgr.GetNames();//doc.GetCustomInfoNames() as object[];
if(objs is string[] names)
{
int len = names.Length;
for (int i = 0; i < len; i++)
{
String strProName = names[i] as String;
if (String.Compare(strAttriName, strProName, true) == 0)
{
return true;
}
}
}
return false;
}
#endregion
/// <summary>
///
/// </summary>
/// <returns></returns>
private static bool InitTable()
{
if (!IsOfficeExcelInstalled())
{
return false;
}
if (previewTable == null)
{
previewTable = new System.Data.DataTable();
previewTable.Columns.Add("实例的classname");
previewTable.Columns.Add("实例的id号");
previewTable.Columns.Add("文件物理路径");
}
previewTable.Clear();
System.Data.DataRow dataRow = previewTable.NewRow();
dataRow[0] = "revision<classname>";
dataRow[1] = "revision<id$>";
dataRow[2] = "fullpath";
previewTable.Rows.Add(dataRow);
return true;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static bool IsOfficeExcelInstalled()
{
Type type = Type.GetTypeFromProgID("Excel.Application");
return type != null;
}
/// <summary>
///
/// </summary>
/// <param name="assemblyFilePath"></param>
/// <param name="fileList"></param>
private static void GetAsmChildren(string assemblyFilePath, ref List<string> fileList)
{
FileType fileType = GetFileType(assemblyFilePath);
if (fileType != FileType.Assembly)
{
return;
}
ModelDoc2 mdlDoc = GetDoc(assemblyFilePath);
if (mdlDoc == null)
{
mdlDoc = OpenDocSilently(assemblyFilePath);
}
if (mdlDoc == null)
{
return;
}
if (!fileList.Contains(assemblyFilePath))
{
fileList.Add(assemblyFilePath);
}
AssemblyDoc asm = mdlDoc as AssemblyDoc;
object[] objs = (object[])asm.GetComponents(true);
if (objs == null)
{
return;
}
int len = objs.Length;
for (int i = 0; i < len; i++)
{
IComponent2 comp = objs[i] as IComponent2;
if (comp != null)
{
String compPathName = comp.GetPathName();
if (!fileList.Contains(compPathName))
{
fileList.Add(compPathName);
GetAsmChildren(compPathName, ref fileList);
}
}
}
return;
}
const string sLicenseKey = "Axemble:swdocmgr_general-11785-02051-00064-50177-08535-34307-00007-37408-17094-12655-31529-39909-49477-26312-14336-58516-10910-42487-02022-02562-54862-24526-57604-46485-45449-00405-25144-23144-51942-23264-24676-28258-7,swdocmgr_previews-11785-02051-00064-50177-08535-34307-00007-48008-04931-27155-53105-52081-64048-22699-38918-23742-63202-30008-58372-23951-37726-23245-57604-46485-45449-00405-25144-23144-51942-23264-24676-28258-1,swdocmgr_dimxpert-11785-02051-00064-50177-08535-34307-00007-16848-46744-46507-43004-11310-13037-46891-59394-52990-24983-00932-12744-51214-03249-23667-57604-46485-45449-00405-25144-23144-51942-23264-24676-28258-8,swdocmgr_geometry-11785-02051-00064-50177-08535-34307-00007-39720-42733-27008-07782-55416-16059-24823-59395-22410-04359-65370-60348-06678-16765-23356-57604-46485-45449-00405-25144-23144-51942-23264-24676-28258-3,swdocmgr_xml-11785-02051-00064-50177-08535-34307-00007-51816-63406-17453-09481-48159-24258-10263-28674-28856-61649-06436-41925-13932-52097-22614-57604-46485-45449-00405-25144-23144-51942-23264-24676-28258-7,swdocmgr_tessellation-11785-02051-00064-50177-08535-34307-00007-13440-59803-19007-55358-48373-41599-14912-02050-07716-07769-29894-19369-42867-36378-24376-57604-46485-45449-00405-25144-23144-51942-23264-24676-28258-0";
//获取属性
public static string GetFamInsAttributeValue(string filePath, string insName, string attributeName)
{
#region
string strlowPath = filePath.ToLower();
if (strlowPath.EndsWith(".slddrw"))
{
return null;
}
ModelDoc2 doc = GetDoc(filePath);
if (doc == null)
{
doc = OpenDocSilently(filePath);
if (doc == null)
{
return null;
}
}
Configuration config = null;
try
{
config = doc.GetConfigurationByName(insName) as Configuration;
}
catch
{
return null;
}
if (config == null)
{
return null;
}
CustomPropertyManager custPropManager = config.CustomPropertyManager;
if (custPropManager == null)
{
return null;
}
string strValOut;
string ResolveValOut;
bool bSuc = custPropManager.Get3(attributeName, true, out strValOut, out ResolveValOut);
return ResolveValOut;
#endregion
#region
//SwDMDocument17 swDocument10 = default(SwDMDocument17);
//try
//{
// SwDMClassFactory swClassFact = default(SwDMClassFactory);
// SwDMApplication swDocMgr = default(SwDMApplication);
// SwDMDocument13 swDocument13 = default(SwDMDocument13);
// SwDmDocumentType nDocType = default(SwDmDocumentType);
// SwDmDocumentOpenError nRetVal = default(SwDmDocumentOpenError);
// nDocType = SwDmDocumentType.swDmDocumentPart;
// swClassFact = new SwDMClassFactory();
// swDocMgr = swClassFact.GetApplication(sLicenseKey);
// swDocument13 = (SwDMDocument13)swDocument10;
// SwDMConfigurationMgr swCfgMgr = default(SwDMConfigurationMgr);
// string[] vCfgNameArr = null;
// SwDMConfiguration14 swCfg = default(SwDMConfiguration14);
// swDocument10 = (SwDMDocument17)swDocMgr.GetDocument(filePath, nDocType, false, out nRetVal);
// if (swDocument10 == null)
// {
// swDocument10 = (SwDMDocument17)swDocMgr.GetDocument(filePath, nDocType, true, out nRetVal);
// if (swDocument10 == null)
// return "";
// }
// swCfgMgr = swDocument10.ConfigurationManager;
// vCfgNameArr = (string[])swCfgMgr.GetConfigurationNames();
// swCfg = (SwDMConfiguration14)swCfgMgr.GetConfigurationByName(swCfgMgr.GetActiveConfigurationName());
// swCfg.GetAllCustomPropertyNamesAndValues(out object names, out object types, out object linkedTos, out object values);
// string[] valueArry = (string[])linkedTos;
// string[] namesArry = (string[])names;
// string attributeValue = "";
// for (int i = 0; i < valueArry.Length; i++)
// {
// if (attributeName == namesArry[i])
// {
// attributeValue = valueArry[i];
// }
// }
// swDocument10.CloseDoc();
// return attributeValue;
//}
//catch (Exception ee)
//{
// if (swDocument10 != null)
// {
// swDocument10.CloseDoc();
// }
// MessageBox.Show(ee.Message);
// return "";
//}
#endregion
}
//设置属性
public static bool SetFamInsAttributeValue(string filePath, string insName, string attributeName, string attributeValue)
{
string strlowPath = filePath.ToLower();
if (strlowPath.EndsWith(".slddrw"))
{
return false;
}
ModelDoc2 doc = GetDoc(filePath);
if (doc == null)
{
doc = OpenDocSilently(filePath);
if (doc == null)
{
return false;
}
}
Configuration config = null;
try
{
config = doc.GetConfigurationByName(insName) as Configuration;
}
catch
{
return false;
}
if (config == null)
{
return false;
}
CustomPropertyManager custPropManager = config.CustomPropertyManager;
if (custPropManager == null)
{
return false;
}
// 0 if the value for the existing custom property is set, 1 if not
int iSuc = custPropManager.Set(attributeName, attributeValue);
if (iSuc == -1) // not exist
{
iSuc = custPropManager.Add2(attributeName, (int)swCustomInfoType_e.swCustomInfoText, attributeValue);
}
return iSuc == 0;
}
public static bool IsAvtiveDocDirty()
{
ISldWorks app = util.application;
ModelDoc2 doc = (ModelDoc2)app.ActiveDoc;
return doc.GetSaveFlag();
}
private static Mouse swMouse = null;
public static bool GetMouseXYZ(string filePath, ref float x, ref float y, ref float z)
{
ModelDoc2 doc = GetDoc(filePath);
if (doc == null)
{
doc = OpenDoc(filePath, false);
}
if (doc != null)
{
swMouse = ((ModelView)doc.GetFirstModelView()).GetMouse();
if (swMouse != null)
{
swMouse.MouseLBtnDownNotify -= ms_MouseLBtnDownNotify;
swMouse.MouseLBtnDownNotify += ms_MouseLBtnDownNotify;
return true;
}
}
return false;
}
public static bool RepaceAssm(string oldFilePath, string newFilePath, string assemblyFilePath)
{
if (solidWorksDocs == null)
solidWorksDocs = new Dictionary<string, ModelDoc2>();
ModelDoc2 mdlDoc = GetDoc(assemblyFilePath) ?? OpenDocSilently(assemblyFilePath);
//
string newChildName = Path.GetFileNameWithoutExtension(newFilePath);
string childName = Path.GetFileNameWithoutExtension(oldFilePath);
AssemblyDoc assemblyDoc = (AssemblyDoc)mdlDoc;
ModelDocExtension swModelDocExt = (ModelDocExtension)mdlDoc.Extension;
//bool status = swModelDocExt.SelectByID2("prt0210001@asm0210-1", "COMPONENT", 0, 0, 0, false, 0, null, 0);
int errorsRename = 0;//swModelDocExt.RenameDocument("prt0210001-2013");
AssemblyDoc asm = mdlDoc as AssemblyDoc;
object[] objs = (object[])asm.GetComponents(false);
if (objs == null)
{
return false;
}
int len = objs.Length;
for (int i = 0; i < len; i++)
{
IComponent2 comp = objs[i] as IComponent2;
string[] tempCompNames = comp.Name2.Split('/');
string tempCompName = tempCompNames[tempCompNames.Length - 1];
if (comp != null)
{
int indexSuffix = tempCompName.LastIndexOf('-');
string tempName = null;
if (indexSuffix > 0)
tempName = tempCompName.Substring(0, indexSuffix);
if (string.Compare(tempName, childName, true) == 0)
{
comp.Select(false);
errorsRename = swModelDocExt.RenameDocument(newChildName);
break;
}
}
}
changNameForDocMange(oldFilePath, newFilePath);
return true;
}
public static bool RenameChild(string asmPath, string childName, string newChildName)
{
if (!asmPath.ToLower().EndsWith(".sldasm"))
return false;
ModelDoc2 mdlDoc = GetDoc(asmPath);
if (mdlDoc == null)
{
mdlDoc = OpenDocSilently(asmPath);
}
if (mdlDoc == null)
{
return false;
}
ModelDocExtension swModelDocExt = (ModelDocExtension)mdlDoc.Extension;
//bool status = swModelDocExt.SelectByID2("prt0210001@asm0210-1", "COMPONENT", 0, 0, 0, false, 0, null, 0);
int errorsRename = 0;//swModelDocExt.RenameDocument("prt0210001-2013");
AssemblyDoc asm = mdlDoc as AssemblyDoc;
object[] objs = (object[])asm.GetComponents(false);
if (objs == null)
{
return false;
}
int len = objs.Length;
string comPath = "";
for (int i = 0; i < len; i++)
{
IComponent2 comp = objs[i] as IComponent2;
if (comp != null)
{
//TODO:asm中component后缀-1 -2要确认
//if (string.Compare(childName, comp.Name2, true) == 0)
//key对应旧文件名value对应新文件名
if (File.Exists(comp.GetPathName()))
{
//派生的时候将只读属性进行更改
FileInfo fileInfo = new FileInfo(comp.GetPathName());
fileInfo.Attributes = fileInfo.Attributes.ToString().IndexOf("ReadOnly") != -1 ? FileAttributes.Normal : fileInfo.Attributes; //修改只读属性
}
if (comp.Name2.Contains("/"))
{
string[] tempCompNames = comp.Name2.Split('/');
string tempCompName = tempCompNames[tempCompNames.Length - 1];
//foreach (string tempCompName in tempCompNames)
{
int indexSuffix = tempCompName.LastIndexOf('-');
string tempName = null;
if (indexSuffix > 0)
tempName = tempCompName.Substring(0, indexSuffix);
if (string.Compare(tempName, childName, true) == 0)
{
comp.Select(false);
comPath = comp.GetPathName();
errorsRename = swModelDocExt.RenameDocument(newChildName);
break;
}
}
}
else
{
int indexSuffix = comp.Name2.LastIndexOf('-');
string tempName = null;
if (indexSuffix > 0)
tempName = comp.Name2.Substring(0, indexSuffix);
if (string.Compare(tempName, childName, true) == 0)
{
comp.Select(false);
comPath = comp.GetPathName();
errorsRename = swModelDocExt.RenameDocument(newChildName);
break;
}
}
}
}
if (errorsRename != 0 && !string.IsNullOrEmpty(comPath))
{
string newChildNamePath = Path.GetDirectoryName(comPath) + "\\" + newChildName + Path.GetExtension(comPath);
changNameForDocMange(comPath, newChildNamePath);
bool isReplaceComponent = asm.ReplaceComponents(newChildNamePath, "", true, true);
return isReplaceComponent;
}
// swRenameDocumentError_None 0 = Success
if (errorsRename == 0 && !string.IsNullOrEmpty(comPath))
{
string fileName = $"{newChildName}{Path.GetExtension(comPath)}";
string newChildNamePath = Path.Combine(Path.GetDirectoryName(comPath), fileName);
RenameAllChildForParent(asmPath, childName, newChildNamePath);
}
selectedComp = null;
return true;
}
public static bool RenameAllChildForParent(string asmPath, string childName, string newChildNamePath)
{
ModelDoc2 currentDoc = (ModelDoc2)SwApp.ActiveDoc;
var configs = GetConfigData(currentDoc.GetPathName(), new string[] { "CLASSNAME" });
bool isReference = false;
if (configs != null && configs.Length > 0)
{
// 是否为参考零件
isReference = childName.Contains("^") || configs[0] == "参考零件";
}
bool isSuccess = false;
// 对其他装配体进行引用更新
if (isReference) // 参考零件
{
var targetName = childName.Split('^').First();
var openedDocs = SwApp.GetDocuments() as object[];
if (openedDocs != null)
{
foreach (var doc in openedDocs)
{
if (doc is AssemblyDoc)
{
var modelDoc = doc as ModelDoc2;
var assDoc = doc as AssemblyDoc;
var assName = modelDoc.GetTitle();
var componentObjs = assDoc.GetComponents(false) as object[];
if (componentObjs != null)
{
foreach (var component in componentObjs)
{
if (component is Component2)
{
// 对每个装配体下面的零件进行递归引用更新
UpdatePartRefs(assDoc, component as Component2, targetName, newChildNamePath);
}
}
}
}
}
}
}
return isSuccess;
}
public static bool BreakReferences()
{
ModelDoc2 mdlDoc = (ModelDoc2)SwApp.ActiveDoc;
if (mdlDoc == null)
{
return false;
}
if (mdlDoc.GetType() != (int)swDocumentTypes_e.swDocPART)
return false;
ModelDocExtension docExtension = mdlDoc.Extension;
docExtension.BreakAllExternalFileReferences2(true);
return true;
}
public static bool SelectPart(string asmPath, string childName)
{
bool isSelect = false;
if (!asmPath.ToLower().EndsWith(".sldasm"))
return false;
ModelDoc2 mdlDoc = GetDoc(asmPath);
if (mdlDoc == null)
{
mdlDoc = OpenDocSilently(asmPath);
}
if (mdlDoc == null)
{
return false;
}
AssemblyDoc asm = mdlDoc as AssemblyDoc;
object[] objs = (object[])asm.GetComponents(false);
if (objs == null)
{
return false;
}
int len = objs.Length;
for (int i = 0; i < len; i++)
{
IComponent2 comp = objs[i] as IComponent2;
if (comp != null)
{
string[] tempCompNames = comp.Name2.Split('/');
string tempCompName = tempCompNames[tempCompNames.Length - 1];
int indexSuffix = tempCompName.LastIndexOf('-');
string tempName = null;
if (indexSuffix > 0)
tempName = tempCompName.Substring(0, indexSuffix);
if (string.Compare(tempName, Path.GetFileNameWithoutExtension(childName), true) == 0)
{
comp.Select(false);
isSelect = true;
break;
}
}
}
return isSelect;
}
private static string insertInstanceName = null;
private static string insertChildFilePath = null;
private static AssemblyDoc curAsm = null;
private static int ms_MouseLBtnDownNotify(int x, int y, int WParam)
{
try
{
if (curAsm != null)
{
ModelDoc2 childDoc = GetDoc(insertChildFilePath);
#region window坐标转换成SolidWorks坐标
ModelDoc2 asmDoc = SwApp.ActiveDoc as ModelDoc2;
//如果ActiveDoc和curAsm不一致则弹出报错
if (string.Compare(asmDoc.GetPathName(), ((ModelDoc2)curAsm).GetPathName(), true) != 0)
{
//MessageBox.Show("不能在当前激活的装配插入零部件,请检查");
return -1;
}
ModelView asmView = asmDoc.ActiveView as ModelView;
MathUtility mathUtil = SwApp.GetMathUtility() as MathUtility;
double[] nPoint = new double[3];
object vPoint = null;
nPoint[0] = x;
nPoint[1] = y;
nPoint[2] = 0;
vPoint = nPoint;
MathPoint swMathPoint = (MathPoint)mathUtil.CreatePoint(vPoint);
MathPoint newSwPoint = swMathPoint.MultiplyTransform(asmView.Transform.Inverse()) as MathPoint;
#endregion
double[] dPoint = new double[3];
dPoint = newSwPoint.ArrayData as double[];
if (childDoc == null)
{
childDoc = OpenDocSilently(insertChildFilePath);
if (childDoc == null)
{
swMouse = asmView.GetMouse();
if (swMouse != null)
{
swMouse.MouseLBtnDownNotify -= ms_MouseLBtnDownNotify;
}
//string strException = Session.MSR.GetString("UI_TEXT_CANNOT_OPEN_FILE");
//if (MessageBox.Show(insertChildFilePath + ":" + strException) == DialogResult.OK)
// SwAddin.Insert();
return 1;
}
}
if (string.IsNullOrEmpty(insertInstanceName))
{
curAsm.AddComponent(insertChildFilePath, dPoint[0], dPoint[1], dPoint[2]);
}
else
{
curAsm.AddComponent4(insertChildFilePath, insertInstanceName, dPoint[0], dPoint[1], dPoint[2]);
}
swMouse = asmView.GetMouse();
if (swMouse != null)
swMouse.MouseLBtnDownNotify -= ms_MouseLBtnDownNotify;
//SwAddin.Insert();
}
return 1;
}
catch (Exception ex)
{
//MessageBox.Show("ms_MouseLBtnDownNotify exception :" + ex.Message);
//Util.LogFile.WriteMessageToLog(ex.StackTrace);
return -1;
}
}
/// <summary>
///
/// </summary>
/// <param name="dic"></param>
/// <param name="targetPath"></param>
/// <param name="assemblyFilePath"></param>
/// <returns></returns>
public static bool PackAndGo(Dictionary<string, string> dic, string targetPath, string assemblyFilePath)
{
if (solidWorksDocs == null)
solidWorksDocs = new Dictionary<string, ModelDoc2>();
ModelDoc2 mdlDoc = GetDoc(assemblyFilePath) ?? OpenDocSilently(assemblyFilePath);
if (!solidWorksDocs.ContainsKey(assemblyFilePath))
solidWorksDocs.Add(assemblyFilePath, mdlDoc);
AssemblyDoc asm = mdlDoc as AssemblyDoc;
if (mdlDoc == null) return false;
PackAndGo swPackAndGo = mdlDoc.Extension.GetPackAndGo();
swPackAndGo.IncludeDrawings = true;
int namesCount = swPackAndGo.GetDocumentNamesCount();
if (swPackAndGo.GetDocumentNames(out object fileNames))
{
string[] pgFileNames = (string[])fileNames;
List<string> outFileNames = new List<string>();
foreach (string tempPath in pgFileNames)
{
string oldFilePath = tempPath.ToUpper();
try
{
outFileNames.Add(oldFilePath.Replace(Path.GetFileNameWithoutExtension(oldFilePath),
dic[oldFilePath]));
}
catch (Exception e)
{
outFileNames.Add(oldFilePath);
}
}
swPackAndGo.SetDocumentSaveToNames(outFileNames.ToArray());
if (swPackAndGo.SetSaveToName(true, targetPath))
{
int[] statuses = (int[])mdlDoc.Extension.SavePackAndGo(swPackAndGo);
return true;
}
}
return false;
}
private static bool changNameForDocMange(string oldPartPath, string newPartPath)
{
try
{
string oldDrawingPath = oldPartPath.Substring(0, oldPartPath.Length - 7) + ".SLDDRW";
string newDrawingPath = newPartPath.Substring(0, newPartPath.Length - 7) + ".SLDDRW";
if (File.Exists(oldDrawingPath))
{
CloseDocument(oldDrawingPath);
File.Copy(oldDrawingPath, newDrawingPath, true);
}
File.Copy(oldPartPath, newPartPath, true);
if (!File.Exists(newPartPath))
{
return false;
}
SwDMClassFactory swClassFact = default(SwDMClassFactory);
SwDMApplication swDocMgr = default(SwDMApplication);
SwDMDocument swDoc = default(SwDMDocument);
SwDMDocument10 swDoc10 = default(SwDMDocument10);
SwDMDocument13 swDoc22 = default(SwDMDocument13);
SwDmDocumentType nDocType = 0;
SwDmDocumentOpenError nRetVal = 0;
if (newDrawingPath.ToLower().EndsWith("slddrw"))
{
nDocType = SwDmDocumentType.swDmDocumentDrawing;
}
else
{
return false;
}
swClassFact = new SwDMClassFactory();
swDocMgr = (SwDMApplication)swClassFact.GetApplication(sLicenseKey);
swDoc = (SwDMDocument)swDocMgr.GetDocument(newDrawingPath, nDocType, false, out nRetVal);
if (swDoc == null)
{
return false;
}
swDoc22 = (SwDMDocument13)swDoc;
object vBrokenRefs = null;
object vIsVirtuals = null;
object vTimeStamps = null;
string[] vDependArr = null;
SwDMSearchOption swSearchOpt = default(SwDMSearchOption);
swSearchOpt = swDocMgr.GetSearchOptionObject();
vDependArr = (string[])swDoc22.GetAllExternalReferences4(swSearchOpt, out vBrokenRefs, out vIsVirtuals, out vTimeStamps);
if ((vDependArr == null)) return false;
var doc16 = (SwDMDocument16)swDoc;
doc16.ReplaceReference(vDependArr[0], newPartPath);
swDoc.Save();
swDoc.CloseDoc();
return true;
}
catch (Exception)
{
throw;
}
}
public static bool ChangdrawRelyOn(string oldPartPath, string newPartPath)
{
try
{
string oldDrawingPath = oldPartPath.Substring(0, oldPartPath.Length - 7) + ".SLDDRW";
string newDrawingPath = newPartPath.Substring(0, newPartPath.Length - 7) + ".SLDDRW";
if (File.Exists(oldDrawingPath))
{
File.Copy(oldDrawingPath, newDrawingPath, true);
}
// File.Copy(oldPartPath, newPartPath, true);
if (!File.Exists(newPartPath))
{
return false;
}
SwDMClassFactory swClassFact = default(SwDMClassFactory);
SwDMApplication swDocMgr = default(SwDMApplication);
SwDMDocument swDoc = default(SwDMDocument);
SwDMDocument10 swDoc10 = default(SwDMDocument10);
SwDMDocument13 swDoc22 = default(SwDMDocument13);
SwDmDocumentType nDocType = 0;
SwDmDocumentOpenError nRetVal = 0;
if (newDrawingPath.ToLower().EndsWith("slddrw"))
{
nDocType = SwDmDocumentType.swDmDocumentDrawing;
}
else
{
return false;
}
swClassFact = new SwDMClassFactory();
swDocMgr = (SwDMApplication)swClassFact.GetApplication(sLicenseKey);
swDoc = (SwDMDocument)swDocMgr.GetDocument(newDrawingPath, nDocType, false, out nRetVal);
if (swDoc == null)
{
return false;
}
swDoc22 = (SwDMDocument13)swDoc;
object vBrokenRefs = null;
object vIsVirtuals = null;
object vTimeStamps = null;
string[] vDependArr = null;
SwDMSearchOption swSearchOpt = default(SwDMSearchOption);
swSearchOpt = swDocMgr.GetSearchOptionObject();
vDependArr = (string[])swDoc22.GetAllExternalReferences4(swSearchOpt, out vBrokenRefs, out vIsVirtuals, out vTimeStamps);
if ((vDependArr == null)) return false;
var doc16 = (SwDMDocument16)swDoc;
doc16.ReplaceReference(vDependArr[0], newPartPath);
swDoc.Save();
swDoc.CloseDoc();
if (File.Exists(newDrawingPath))
{
int errors = 0;
int warnings = 0;
// 刷新新图纸 以免出现零件模型更新后图纸未更新
OpenDocument(newDrawingPath, true);
var oldDraw = SwApp.ActiveDoc as ModelDoc2;
if (oldDraw != null && oldDraw.GetType() == (int)swDocumentTypes_e.swDocDRAWING)
{
var drawDoc = oldDraw as DrawingDoc;
var sheetName = (drawDoc.GetSheetNames() as string[])[0];
drawDoc.ActivateSheet(sheetName);
var drawExt = oldDraw.Extension;
// 重建只在文档可见的时候有效,如果设置了Visible = false或者使用静默打开文档那么重建是无效的
drawExt.Rebuild((int)swRebuildOptions_e.swCurrentSheetDisp);
oldDraw.ForceRebuild3(false);
oldDraw.Save(); // 只有这个函数能够正常保存
CloseDocument(newDrawingPath);
}
}
CloseDocument(newDrawingPath);
return true;
}
catch (Exception)
{
throw;
}
}
public static int[] OnlyPack(string[] outFileNames, string targetPath, string assemblyFilePath)
{
if (solidWorksDocs == null)
solidWorksDocs = new Dictionary<string, ModelDoc2>();
ModelDoc2 mdlDoc = GetDoc(assemblyFilePath) ?? OpenDocSilently(assemblyFilePath);
if (!solidWorksDocs.ContainsKey(assemblyFilePath))
solidWorksDocs.Add(assemblyFilePath, mdlDoc);
PackAndGo swPackAndGo = mdlDoc.Extension.GetPackAndGo();
swPackAndGo.IncludeDrawings = true;
swPackAndGo.SetDocumentSaveToNames(outFileNames);
if (swPackAndGo.SetSaveToName(true, targetPath))
{
int[] statuses = (int[])mdlDoc.Extension.SavePackAndGo(swPackAndGo);
return statuses;
}
return null;
}
public static string[] OutPackPath(string assemblyFilePath)
{
if (solidWorksDocs == null)
solidWorksDocs = new Dictionary<string, ModelDoc2>();
ModelDoc2 mdlDoc = GetDoc(assemblyFilePath) ?? OpenDocSilently(assemblyFilePath);
if (!solidWorksDocs.ContainsKey(assemblyFilePath))
solidWorksDocs.Add(assemblyFilePath, mdlDoc);
PackAndGo swPackAndGo = mdlDoc.Extension.GetPackAndGo();
swPackAndGo.IncludeDrawings = true;
swPackAndGo.GetDocumentNames(out object fileNames);
string[] pgFileNames = (string[])fileNames;
return pgFileNames;
}
public static bool EditRebuild(string assemblyFilePath)
{
if (solidWorksDocs == null)
solidWorksDocs = new Dictionary<string, ModelDoc2>();
ModelDoc2 mdlDoc = GetDoc(assemblyFilePath) ?? OpenDocSilently(assemblyFilePath);
bool Rebuild = mdlDoc.EditRebuild3();
return Rebuild;
}
/// <summary>
/// 是否为参考零件
/// </summary>
/// <param name="component"></param>
/// <param name="partName"></param>
/// <returns></returns>
private static bool isReferencePart(IComponent2 component, string partName)
{
bool isReference = false;
var componentName = component.Name2.Split('/').LastOrDefault();
var className = GetConfigData(component.GetPathName(), new string[] { "CLASSNAME" })?.FirstOrDefault() ?? "";
if (className == "参考零件" || componentName.Contains("^"))
{
isReference = true;
}
return isReference;
}
/// <summary>
/// 更新参考零件的所有引用
/// </summary>
/// <param name="topComponent">在整个设备打开时获取到的装配体对象</param>
/// <param name="partName">查找的文件名(不建议包含“^”符号之后的字符)</param>
/// <param name="isStartWith">是否以partName为起始查找 -> string.StartsWith </param>
/// <returns>返回异常信息</returns>
private static void UpdatePartRefs(AssemblyDoc assembly, Component2 topComponent, string partName, string newPartFilePath, bool isStartWith = true)
{
var children = topComponent.GetChildren();
if (children != null)
{
object[] childrenObjects = children as object[];
foreach (var componentObject in childrenObjects)
{
bool selected = false;
if (componentObject is Component2)
{
var component = componentObject as Component2;
var component2 = componentObject as IComponent2;
var componentName = component.Name2.Split('/').LastOrDefault();
if (isReferencePart(component2, componentName))
{
if (isStartWith)
{
if (componentName.StartsWith(partName))
{
component.Select4(true, null, false);
selected = true;
}
}
else
{
if (partName == componentName)
{
component.Select4(true, null, false);
selected = true;
}
}
// 存在选中的零件,使用新的文件路径替换
if (selected) assembly.ReplaceComponents(newPartFilePath, "", true, true);
}
else
{
UpdatePartRefs(assembly, component, partName, newPartFilePath, isStartWith);
}
}
}
}
}
public static void OutPackPath(string assemblyFilePath, bool includeDwg, string targetAsmFolder,
string AddPrefix,
string AddSuffix)
{
try
{
//ModelDoc2 swModelDoc = default(ModelDoc2);
ModelDoc2 swModelDoc = GetDoc(assemblyFilePath) ?? OpenDocSilently(assemblyFilePath);
string[] pgFileNames = { };
List<string> strings = new List<string>();
bool status = false;
int warnings = 0;
int errors = 0;
int i = 0;
string myPath = null;
int[] statuses = null;
ModelDocExtension swModelDocExt = (ModelDocExtension)swModelDoc.Extension;
PackAndGo swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo();
var namesCount = swPackAndGo.GetDocumentNamesCount();
swPackAndGo.IncludeDrawings = includeDwg;
swPackAndGo.IncludeSimulationResults = true;
swPackAndGo.IncludeToolboxComponents = true;
swPackAndGo.IncludeDrawings = true;
//swPackAndGo.IncludeToolboxComponents = true;
swModelDocExt = (ModelDocExtension)swModelDoc.Extension;
swPackAndGo.GetDocumentNames(out object fileNames);
pgFileNames = (string[])fileNames;
object pgFileStatus;
swPackAndGo.GetDocumentSaveToNames(out fileNames, out pgFileStatus);
bool a = swPackAndGo.SetSaveToName(true, targetAsmFolder);
swPackAndGo.FlattenToSingleFolder = true;
swPackAndGo.AddPrefix = AddPrefix;
swPackAndGo.AddSuffix = AddSuffix;
object getFileNames;
object getDocumentStatus;
string[] pgGetFileNames = new string[namesCount - 1];
status = swPackAndGo.GetDocumentSaveToNames(out getFileNames, out getDocumentStatus);
pgGetFileNames = (string[])getFileNames;
swPackAndGo.SetDocumentSaveToNames(pgGetFileNames);
// 执行打包。
swModelDocExt.SavePackAndGo(swPackAndGo);
SwApp.CloseDoc(SwApp.IActiveDoc2.GetPathName());
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
public static ModelDoc2 ActiveDoc()
{
var modeldoc = SwApp.ActiveDoc;
return (ModelDoc2)modeldoc;
}
public static void RepalComponent(string asmName, string start, string end)
{
//首先打开 TempAssembly.sldasm
//运行后,程序会把装配体中的Clamp1零件替换成Clamp2
SwApp.OpenDoc(asmName, 1);
ModelDoc2 swModel = (ModelDoc2)SwApp.ActiveDoc;
ModelDocExtension swModelDocExt = (ModelDocExtension)swModel.Extension;
SelectionMgr selectionMgr = (SelectionMgr)swModel.SelectionManager;
AssemblyDoc assemblyDoc = (AssemblyDoc)swModel;
//替换为同目录下的clamp2
string ReplacePartPath = Path.GetDirectoryName(swModel.GetPathName()) + $@"\{end}";
bool boolstatus;
//选择当前的clamp1
boolstatus = swModelDocExt.SelectByID2($"{start}", "COMPONENT", 0, 0, 0, false, 0, null, 0);
boolstatus = assemblyDoc.ReplaceComponents(ReplacePartPath, "默认", true, true);
if (boolstatus == true)
{
SwApp.CloseDoc(asmName);
}
}
public static void GenerateRandomJJJPropForAllParts()
{
try
{
var openedDocs = SwApp.GetDocuments() as object[];
if (openedDocs != null)
{
foreach (var doc in openedDocs)
{
if (doc is IModelDoc2)
{
var modelDoc = doc as IModelDoc2;
if (modelDoc.GetType() == (int)swDocumentTypes_e.swDocPART)
{
var partDoc = modelDoc as IPartDoc;
var modelDocExt = modelDoc.Extension;
var customPropMgr = modelDocExt.get_CustomPropertyManager("");
// 生成随机数
Random random = new Random();
int randomValue = random.Next(1000, 9999);
// 设置自定义属性JJJ_PROP
//customPropMgr.Set2("JJJ_PROP", randomValue.ToString());
SWUtils.SetAttributeValue(modelDoc.GetPathName(), "JJJ_Prop", randomValue.ToString());
modelDoc.Save();
Console.WriteLine($"Model name: {modelDoc.GetPathName()}, JJJ_Prop: {randomValue}");
}
}
}
}
}
catch (Exception)
{
throw;
}
}
public static Dictionary<string, string> GetConfig2(string partPath, string[] CustomPropertyNames)
{
Dictionary<string, string> dicDeriveModel = new Dictionary<string, string>();
ISwDMDocument swDocument10 = null;
Dictionary<string, string> dictionary;
try
{
SwDmDocumentOpenError nRetVal = SwDmDocumentOpenError.swDmDocumentOpenErrorNone;
SwDmDocumentType nDocType = SwDmDocumentType.swDmDocumentPart;
SwDMClassFactory swClassFact = new SwDMClassFactory();
SwDMApplication2 swDocMgr = (SwDMApplication2)swClassFact.GetApplication("82EC0E04A67C7A48A3AB757A947C507A8210C1E87738B58E");
SwDMDocument13 swDocument11 = (SwDMDocument13)swDocument10;
swDocument10 = swDocMgr.GetDocument(partPath, nDocType, false, out nRetVal);
bool flag = swDocument10 == null;
if (flag)
{
swDocument10 = swDocMgr.GetDocument(partPath, nDocType, true, out nRetVal);
}
ISwDMConfigurationMgr swCfgMgr = swDocument10.ConfigurationManager;
string ActiveConfigurationName = swCfgMgr.GetActiveConfigurationName();
bool flag2 = string.IsNullOrWhiteSpace(ActiveConfigurationName);
if (flag2)
{
dictionary = dicDeriveModel;
}
else
{
ISwDMConfiguration12 swCfg = (ISwDMConfiguration12)swCfgMgr.GetConfigurationByName(ActiveConfigurationName);
object names;
object types;
object linkedTos;
object values;
swCfg.GetAllCustomPropertyNamesAndValues(out names, out types, out linkedTos, out values);
string[] valueArry = (string[])linkedTos;
string[] namesArry = (string[])names;
bool flag3 = valueArry != null;
if (flag3)
{
for (int i = 0; i < valueArry.Length; i++)
{
foreach (string CustomPropertyName in CustomPropertyNames)
{
bool flag4 = CustomPropertyName == namesArry[i];
if (flag4)
{
dicDeriveModel.Add(CustomPropertyName, valueArry[i]);
}
}
}
}
swDocument10.CloseDoc();
dictionary = dicDeriveModel;
}
}
catch (Exception ee)
{
bool flag5 = swDocument10 != null;
if (flag5)
{
swDocument10.CloseDoc();
}
dictionary = dicDeriveModel;
}
return dictionary;
}
public static Dictionary<string, string> GetConfig3(string filePath)
{
var result = new Dictionary<string, string>();
if (string.IsNullOrEmpty(filePath))
{
return result;
}
var model = OpenDocSilently(filePath);
if(model is null)
{
return result;
}
// 1) 先读取文件级自定义属性Custom tab
try
{
var modelExt = model.Extension;
if (modelExt != null)
{
CustomPropertyManager filePropMgr = modelExt.get_CustomPropertyManager("");
if (filePropMgr != null)
{
var filePropertyNames = filePropMgr.GetNames() as string[];
if (filePropertyNames != null)
{
foreach (var propName in filePropertyNames)
{
if (string.IsNullOrEmpty(propName))
{
continue;
}
string val;
string resolvedVal;
bool wasResolved;
filePropMgr.Get5(propName, false, out val, out resolvedVal, out wasResolved);
result[propName] = resolvedVal;
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("GetConfig3 file-level props error: " + ex.ToString());
}
// 2) 再读取配置特定属性Configuration Specific tab同名键覆盖文件级属性
var activeConfig = model.GetActiveConfiguration();
if(activeConfig != null && activeConfig is Configuration config)
{
try
{
var propertyManager = config.CustomPropertyManager;
var propertyNames = propertyManager?.GetNames() as string[];
if (propertyNames != null)
{
foreach (var propName in propertyNames)
{
if (string.IsNullOrEmpty(propName))
{
continue;
}
string val;
string resolvedVal;
bool wasResolved;
propertyManager.Get5(propName, false, out val, out resolvedVal, out wasResolved);
result[propName] = resolvedVal;
}
}
}
catch (Exception ex)
{
Debug.WriteLine("GetConfig3 config-level props error: " + ex.ToString());
}
}
return result;
}
public static List<SwAssDocTreeModel> GetSwAssDocTreeChildren(Component2 topComponent, bool disableRefPart, bool disableOutSourcing, int dept = -1)
{
object[] topComponentChildren = topComponent.GetChildren() as object[];
string topComponentName = Path.GetFileNameWithoutExtension(topComponent.GetPathName());
//Function.updateProgress(5, 3, topComponentName);
Dictionary<string, string> props = GetConfig3(topComponent.GetPathName());
string syncConfigName = "";
try
{
var tmpDoc = GetDoc(topComponent.GetPathName()) ?? OpenDocSilently(topComponent.GetPathName());
if (tmpDoc != null)
{
var tmpCfg = tmpDoc.ConfigurationManager?.ActiveConfiguration;
if (tmpCfg != null)
{
syncConfigName = tmpCfg.Name ?? "";
}
}
}
catch { }
string className = props.TryGet("属性");
bool isOutSourcing = className.EndsWith("标准件");
bool isParent = topComponentChildren == null || (topComponentChildren != null && topComponentChildren.Length != 0);
bool isReference = className.Equals("参考零件");
//bool flag2 = string.IsNullOrEmpty(className);
//if (flag2)
//{
// isReference = topComponentName.Contains("^");
//}
bool isDuplicatePart = topComponentName.StartsWith("复件") || topComponentName.StartsWith("Copy of");
bool flag3 = (isReference && disableRefPart) || isDuplicatePart;
List<SwAssDocTreeModel> list;
if (flag3)
{
list = new List<SwAssDocTreeModel>();
}
else
{
bool flag4 = !isParent || (disableOutSourcing && isOutSourcing) || dept == 0;
if (flag4)
{
list = new List<SwAssDocTreeModel>
{
new SwAssDocTreeModel
{
drawingNo = topComponentName,
docPath = topComponent.GetPathName(),
configName = syncConfigName,
isAss = (topComponentChildren == null || topComponentChildren.Length != 0),
isOutSourcing = isOutSourcing,
props = props,
quantity = 1
}
};
}
else
{
List<SwAssDocTreeModel> swAssDocTreeModels = new List<SwAssDocTreeModel>();
bool flag5 = topComponentChildren == null;
if (flag5)
{
list = swAssDocTreeModels;
}
else
{
object[] array = topComponentChildren;
for (int j = 0; j < array.Length; j++)
{
object component = array[j];
Component2 component2 = component as Component2;
string drawingNo = Path.GetFileNameWithoutExtension(component2.GetPathName());
bool flag6 = swAssDocTreeModels.Any((SwAssDocTreeModel i) => i.drawingNo == drawingNo);
if (flag6)
{
SwAssDocTreeModel swAssDocTreeModel = swAssDocTreeModels.First((SwAssDocTreeModel i) => i.drawingNo == drawingNo);
int quantity = swAssDocTreeModel.quantity;
swAssDocTreeModel.quantity = quantity + 1;
}
else
{
using (List<SwAssDocTreeModel>.Enumerator enumerator = GetSwAssDocTreeChildren(component2, disableRefPart, disableOutSourcing, dept - 1).GetEnumerator())
{
while (enumerator.MoveNext())
{
SwAssDocTreeModel item = enumerator.Current;
bool flag7 = swAssDocTreeModels.Contains(item);
if (flag7)
{
SwAssDocTreeModel exItem = swAssDocTreeModels.Where((SwAssDocTreeModel it) => it.drawingNo == item.drawingNo).FirstOrDefault<SwAssDocTreeModel>();
bool flag8 = exItem != null;
if (flag8)
{
exItem.quantity++;
}
}
else
{
bool flag9 = MateMap.ContainsKey(item.drawingNo);
if (flag9)
{
item.swMateCount = MateMap[item.drawingNo];
}
swAssDocTreeModels.Add(item);
}
}
}
}
}
list = new List<SwAssDocTreeModel>
{
new SwAssDocTreeModel
{
drawingNo = topComponentName,
docPath = topComponent.GetPathName(),
configName = syncConfigName,
children = swAssDocTreeModels.ToList<SwAssDocTreeModel>(),
isAss = true,
props = props,
quantity = 1
}
};
}
}
}
return list;
}
public static Task<List<SwAssDocTreeModel>> GetSwAssDocTreeChildrenAsync(Component2 topComponent, bool disableRefPart, bool disableOutSourcing, int totalCount, IProgress<SwTreeLoadProgress> progress = null, int dept = -1)
{
var progressState = new SwTreeLoadProgressState(totalCount, progress);
return GetSwAssDocTreeChildrenAsync(topComponent, disableRefPart, disableOutSourcing, dept, progressState);
}
private static async Task<List<SwAssDocTreeModel>> GetSwAssDocTreeChildrenAsync(Component2 topComponent, bool disableRefPart, bool disableOutSourcing, int dept, SwTreeLoadProgressState progressState)
{
await ReportTreeLoadProgressAsync(topComponent, progressState);
object[] topComponentChildren = topComponent.GetChildren() as object[];
string topComponentName = Path.GetFileNameWithoutExtension(topComponent.GetPathName());
Dictionary<string, string> props = GetConfig3(topComponent.GetPathName());
string activeConfigName = "";
try
{
var tmpDoc = GetDoc(topComponent.GetPathName()) ?? OpenDocSilently(topComponent.GetPathName());
if (tmpDoc != null)
{
var tmpCfg = tmpDoc.ConfigurationManager?.ActiveConfiguration;
if (tmpCfg != null)
{
activeConfigName = tmpCfg.Name ?? "";
}
}
}
catch { }
string className = props.TryGet("属性");
bool isOutSourcing = className.EndsWith("标准件");
bool isParent = topComponentChildren == null || (topComponentChildren != null && topComponentChildren.Length != 0);
bool isReference = className.Equals("参考零件");
bool isDuplicatePart = topComponentName.StartsWith("复件") || topComponentName.StartsWith("Copy of");
bool flag3 = (isReference && disableRefPart) || isDuplicatePart;
if (flag3)
{
return new List<SwAssDocTreeModel>();
}
bool flag4 = !isParent || (disableOutSourcing && isOutSourcing) || dept == 0;
if (flag4)
{
return new List<SwAssDocTreeModel>
{
new SwAssDocTreeModel
{
drawingNo = topComponentName,
docPath = topComponent.GetPathName(),
configName = activeConfigName,
isAss = (topComponentChildren == null || topComponentChildren.Length != 0),
isOutSourcing = isOutSourcing,
props = props,
quantity = 1
}
};
}
List<SwAssDocTreeModel> swAssDocTreeModels = new List<SwAssDocTreeModel>();
if (topComponentChildren == null)
{
return swAssDocTreeModels;
}
object[] array = topComponentChildren;
for (int j = 0; j < array.Length; j++)
{
Component2 component2 = array[j] as Component2;
if (component2 == null)
{
continue;
}
string drawingNo = Path.GetFileNameWithoutExtension(component2.GetPathName());
bool flag6 = swAssDocTreeModels.Any((SwAssDocTreeModel i) => i.drawingNo == drawingNo);
if (flag6)
{
SwAssDocTreeModel swAssDocTreeModel = swAssDocTreeModels.First((SwAssDocTreeModel i) => i.drawingNo == drawingNo);
int quantity = swAssDocTreeModel.quantity;
swAssDocTreeModel.quantity = quantity + 1;
}
else
{
List<SwAssDocTreeModel> childItems = await GetSwAssDocTreeChildrenAsync(component2, disableRefPart, disableOutSourcing, dept - 1, progressState);
using (List<SwAssDocTreeModel>.Enumerator enumerator = childItems.GetEnumerator())
{
while (enumerator.MoveNext())
{
SwAssDocTreeModel item = enumerator.Current;
bool flag7 = swAssDocTreeModels.Contains(item);
if (flag7)
{
SwAssDocTreeModel exItem = swAssDocTreeModels.Where((SwAssDocTreeModel it) => it.drawingNo == item.drawingNo).FirstOrDefault<SwAssDocTreeModel>();
bool flag8 = exItem != null;
if (flag8)
{
exItem.quantity++;
}
}
else
{
bool flag9 = MateMap.ContainsKey(item.drawingNo);
if (flag9)
{
item.swMateCount = MateMap[item.drawingNo];
}
swAssDocTreeModels.Add(item);
}
}
}
}
}
return new List<SwAssDocTreeModel>
{
new SwAssDocTreeModel
{
drawingNo = topComponentName,
docPath = topComponent.GetPathName(),
configName = activeConfigName,
children = swAssDocTreeModels.ToList<SwAssDocTreeModel>(),
isAss = true,
props = props,
quantity = 1
}
};
}
private static async Task ReportTreeLoadProgressAsync(Component2 component, SwTreeLoadProgressState progressState)
{
if (component == null || progressState == null)
{
return;
}
progressState.Processed++;
progressState.Progress?.Report(new SwTreeLoadProgress
{
Processed = progressState.Processed,
Total = progressState.Total,
CurrentName = Path.GetFileNameWithoutExtension(component.GetPathName())
});
progressState.YieldCount++;
if (progressState.YieldCount % 5 == 0)
{
await Task.Yield();
}
}
private sealed class SwTreeLoadProgressState
{
public SwTreeLoadProgressState(int total, IProgress<SwTreeLoadProgress> progress)
{
Total = total <= 0 ? 1 : total;
Progress = progress;
}
public int Processed { get; set; }
public int Total { get; }
public int YieldCount { get; set; }
public IProgress<SwTreeLoadProgress> Progress { get; }
}
public static List<BomItemModel> FlattenBomTree(SwAssDocTreeModel root)
{
var result = new List<BomItemModel>();
var allPropKeys = new HashSet<string>();
int nextNodeId = 0;
FlattenBomTreeRecursive(root, 0, "", -1, ref nextNodeId, result, allPropKeys);
return result;
}
public static HashSet<string> CollectAllPropertyKeys(List<BomItemModel> bomItems)
{
var keys = new HashSet<string>();
foreach (var item in bomItems)
{
if (item.Props != null)
{
foreach (var key in item.Props.Keys)
{
keys.Add(key);
}
}
}
return keys;
}
private static void FlattenBomTreeRecursive(SwAssDocTreeModel node, int level, string parentIndex, int parentNodeId, ref int nextNodeId, List<BomItemModel> result, HashSet<string> allPropKeys)
{
if (node == null)
{
return;
}
int currentNodeId = nextNodeId++;
bool hasChildren = node.children != null && node.children.Count > 0;
string levelDisplay = parentIndex;
var bomItem = new BomItemModel
{
Level = level,
LevelDisplay = levelDisplay,
DrawingNo = node.drawingNo ?? "",
ConfigName = node.configName ?? "",
PartName = node.props.TryGet("零件名称"),
MaterialProp = node.props.TryGet("材料"),
Material = node.props.TryGet("材质"),
Classification = node.props.TryGet("属性"),
Quantity = node.quantity,
IsAssembly = node.isAss,
IsOutSourcing = node.isOutSourcing,
DocPath = node.docPath ?? "",
Props = node.props ?? new Dictionary<string, string>(),
NodeId = currentNodeId,
ParentNodeId = parentNodeId,
HasChildren = hasChildren,
IsExpanded = true,
IsVisible = true
};
if (bomItem.Props != null)
{
foreach (var key in bomItem.Props.Keys)
{
allPropKeys.Add(key);
}
}
result.Add(bomItem);
if (hasChildren)
{
for (int i = 0; i < node.children.Count; i++)
{
string childIndex = string.IsNullOrEmpty(parentIndex)
? (i + 1).ToString()
: parentIndex + "." + (i + 1);
FlattenBomTreeRecursive(node.children[i], level + 1, childIndex, currentNodeId, ref nextNodeId, result, allPropKeys);
}
}
}
}
public sealed class SwTreeLoadProgress
{
public int Processed { get; set; }
public int Total { get; set; }
public string CurrentName { get; set; }
}
public enum FileType
{
Part, Assembly, Drawing, SheetMetal, Other
}
public static class Extensions
{
public static string TryGet(this Dictionary<string, string> dic, string key)
{
return (dic != null && dic.ContainsKey(key)) ? dic[key] : "";
}
}
}