commit 62b982cf171c84b1bada38852a7c265585458f49 Author: lihanbo Date: Tue Mar 4 11:35:11 2025 +0800 Init commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1c702b5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,289 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +# VS Code +.vscode/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Typescript v1 declaration files +typings/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs \ No newline at end of file diff --git a/AutoSW_bin/AntdUI.dll b/AutoSW_bin/AntdUI.dll new file mode 100644 index 0000000..9c5499d Binary files /dev/null and b/AutoSW_bin/AntdUI.dll differ diff --git a/AutoSW_bin/AutoSW.Agent.dll b/AutoSW_bin/AutoSW.Agent.dll new file mode 100644 index 0000000..256b4fe Binary files /dev/null and b/AutoSW_bin/AutoSW.Agent.dll differ diff --git a/AutoSW_bin/AutoSW.UI.dll b/AutoSW_bin/AutoSW.UI.dll new file mode 100644 index 0000000..021d8cb Binary files /dev/null and b/AutoSW_bin/AutoSW.UI.dll differ diff --git a/AutoSW_bin/AutoSW.dll b/AutoSW_bin/AutoSW.dll new file mode 100644 index 0000000..a8805d4 Binary files /dev/null and b/AutoSW_bin/AutoSW.dll differ diff --git a/AutoSW_bin/CompoundFileAttribute.dll b/AutoSW_bin/CompoundFileAttribute.dll new file mode 100644 index 0000000..ca9d95e Binary files /dev/null and b/AutoSW_bin/CompoundFileAttribute.dll differ diff --git a/AutoSW_bin/JumpKick.HttpLib.dll b/AutoSW_bin/JumpKick.HttpLib.dll new file mode 100644 index 0000000..9f8c3f8 Binary files /dev/null and b/AutoSW_bin/JumpKick.HttpLib.dll differ diff --git a/AutoSW_bin/Microsoft.Bcl.AsyncInterfaces.dll b/AutoSW_bin/Microsoft.Bcl.AsyncInterfaces.dll new file mode 100644 index 0000000..cf06e02 Binary files /dev/null and b/AutoSW_bin/Microsoft.Bcl.AsyncInterfaces.dll differ diff --git a/AutoSW_bin/Microsoft.Extensions.AI.Abstractions.dll b/AutoSW_bin/Microsoft.Extensions.AI.Abstractions.dll new file mode 100644 index 0000000..61be10f Binary files /dev/null and b/AutoSW_bin/Microsoft.Extensions.AI.Abstractions.dll differ diff --git a/AutoSW_bin/Microsoft.Extensions.AI.Ollama.dll b/AutoSW_bin/Microsoft.Extensions.AI.Ollama.dll new file mode 100644 index 0000000..d8376f7 Binary files /dev/null and b/AutoSW_bin/Microsoft.Extensions.AI.Ollama.dll differ diff --git a/AutoSW_bin/Microsoft.Extensions.AI.OpenAI.dll b/AutoSW_bin/Microsoft.Extensions.AI.OpenAI.dll new file mode 100644 index 0000000..8555fdb Binary files /dev/null and b/AutoSW_bin/Microsoft.Extensions.AI.OpenAI.dll differ diff --git a/AutoSW_bin/Microsoft.Extensions.AI.dll b/AutoSW_bin/Microsoft.Extensions.AI.dll new file mode 100644 index 0000000..8cb8e89 Binary files /dev/null and b/AutoSW_bin/Microsoft.Extensions.AI.dll differ diff --git a/AutoSW_bin/Microsoft.Extensions.Caching.Abstractions.dll b/AutoSW_bin/Microsoft.Extensions.Caching.Abstractions.dll new file mode 100644 index 0000000..f51e1ec Binary files /dev/null and b/AutoSW_bin/Microsoft.Extensions.Caching.Abstractions.dll differ diff --git a/AutoSW_bin/Microsoft.Extensions.DependencyInjection.Abstractions.dll b/AutoSW_bin/Microsoft.Extensions.DependencyInjection.Abstractions.dll new file mode 100644 index 0000000..3307ba8 Binary files /dev/null and b/AutoSW_bin/Microsoft.Extensions.DependencyInjection.Abstractions.dll differ diff --git a/AutoSW_bin/Microsoft.Extensions.Logging.Abstractions.dll b/AutoSW_bin/Microsoft.Extensions.Logging.Abstractions.dll new file mode 100644 index 0000000..1e010fa Binary files /dev/null and b/AutoSW_bin/Microsoft.Extensions.Logging.Abstractions.dll differ diff --git a/AutoSW_bin/Microsoft.Extensions.Primitives.dll b/AutoSW_bin/Microsoft.Extensions.Primitives.dll new file mode 100644 index 0000000..1ae21b7 Binary files /dev/null and b/AutoSW_bin/Microsoft.Extensions.Primitives.dll differ diff --git a/AutoSW_bin/OpenAI.dll b/AutoSW_bin/OpenAI.dll new file mode 100644 index 0000000..34531bf Binary files /dev/null and b/AutoSW_bin/OpenAI.dll differ diff --git a/AutoSW_bin/System.Buffers.dll b/AutoSW_bin/System.Buffers.dll new file mode 100644 index 0000000..f2d83c5 Binary files /dev/null and b/AutoSW_bin/System.Buffers.dll differ diff --git a/AutoSW_bin/System.ClientModel.dll b/AutoSW_bin/System.ClientModel.dll new file mode 100644 index 0000000..8b60dc3 Binary files /dev/null and b/AutoSW_bin/System.ClientModel.dll differ diff --git a/AutoSW_bin/System.Diagnostics.DiagnosticSource.dll b/AutoSW_bin/System.Diagnostics.DiagnosticSource.dll new file mode 100644 index 0000000..39371ea Binary files /dev/null and b/AutoSW_bin/System.Diagnostics.DiagnosticSource.dll differ diff --git a/AutoSW_bin/System.IO.Pipelines.dll b/AutoSW_bin/System.IO.Pipelines.dll new file mode 100644 index 0000000..8fab8c6 Binary files /dev/null and b/AutoSW_bin/System.IO.Pipelines.dll differ diff --git a/AutoSW_bin/System.Memory.Data.dll b/AutoSW_bin/System.Memory.Data.dll new file mode 100644 index 0000000..a59d969 Binary files /dev/null and b/AutoSW_bin/System.Memory.Data.dll differ diff --git a/AutoSW_bin/System.Memory.dll b/AutoSW_bin/System.Memory.dll new file mode 100644 index 0000000..4617199 Binary files /dev/null and b/AutoSW_bin/System.Memory.dll differ diff --git a/AutoSW_bin/System.Net.Http.Json.dll b/AutoSW_bin/System.Net.Http.Json.dll new file mode 100644 index 0000000..c62521c Binary files /dev/null and b/AutoSW_bin/System.Net.Http.Json.dll differ diff --git a/AutoSW_bin/System.Numerics.Vectors.dll b/AutoSW_bin/System.Numerics.Vectors.dll new file mode 100644 index 0000000..0865972 Binary files /dev/null and b/AutoSW_bin/System.Numerics.Vectors.dll differ diff --git a/AutoSW_bin/System.Runtime.CompilerServices.Unsafe.dll b/AutoSW_bin/System.Runtime.CompilerServices.Unsafe.dll new file mode 100644 index 0000000..c5ba4e4 Binary files /dev/null and b/AutoSW_bin/System.Runtime.CompilerServices.Unsafe.dll differ diff --git a/AutoSW_bin/System.Text.Encodings.Web.dll b/AutoSW_bin/System.Text.Encodings.Web.dll new file mode 100644 index 0000000..5518dbe Binary files /dev/null and b/AutoSW_bin/System.Text.Encodings.Web.dll differ diff --git a/AutoSW_bin/System.Text.Json.dll b/AutoSW_bin/System.Text.Json.dll new file mode 100644 index 0000000..a931ec0 Binary files /dev/null and b/AutoSW_bin/System.Text.Json.dll differ diff --git a/AutoSW_bin/System.Threading.Channels.dll b/AutoSW_bin/System.Threading.Channels.dll new file mode 100644 index 0000000..0e05bbb Binary files /dev/null and b/AutoSW_bin/System.Threading.Channels.dll differ diff --git a/AutoSW_bin/System.Threading.Tasks.Extensions.dll b/AutoSW_bin/System.Threading.Tasks.Extensions.dll new file mode 100644 index 0000000..eeec928 Binary files /dev/null and b/AutoSW_bin/System.Threading.Tasks.Extensions.dll differ diff --git a/AutoSW_bin/System.ValueTuple.dll b/AutoSW_bin/System.ValueTuple.dll new file mode 100644 index 0000000..4ce28fd Binary files /dev/null and b/AutoSW_bin/System.ValueTuple.dll differ diff --git a/AutoSW_bin/assest/edit32.bmp b/AutoSW_bin/assest/edit32.bmp new file mode 100644 index 0000000..ca788b7 Binary files /dev/null and b/AutoSW_bin/assest/edit32.bmp differ diff --git a/AutoSW_bin/solidworkstools.dll b/AutoSW_bin/solidworkstools.dll new file mode 100644 index 0000000..c909f6b Binary files /dev/null and b/AutoSW_bin/solidworkstools.dll differ diff --git a/src/AutoSW.Agent/AIFuncAttribute.cs b/src/AutoSW.Agent/AIFuncAttribute.cs new file mode 100644 index 0000000..1ceebea --- /dev/null +++ b/src/AutoSW.Agent/AIFuncAttribute.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutoSW.Agent; + +[AttributeUsage(AttributeTargets.Method)] +public class AIFuncAttribute : Attribute +{ +} diff --git a/src/AutoSW.Agent/AgentExecutor.cs b/src/AutoSW.Agent/AgentExecutor.cs new file mode 100644 index 0000000..e982657 --- /dev/null +++ b/src/AutoSW.Agent/AgentExecutor.cs @@ -0,0 +1,577 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.Remoting.Metadata.W3cXsd2001; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using AntdUI; +using Microsoft.Extensions.AI; +using SolidWorks.Interop.sldworks; +using SolidWorks.Interop.swconst; +using SolidWorks.Interop.swdimxpert; +using SolidWorks.Interop.swpublished; + +namespace AutoSW.Agent; + +public class AgentExecutor +{ + private static List _allAiFunc = new(); + public static List Funcs = new(); + internal static SldWorks SldWorksApp + { + get; set; + } + public static void Init(SldWorks sld) + { + SldWorksApp = sld; + SWFunctions.SwApp = sld; + Debug.WriteLine("AgentExecutor init"); + + //var funcs = typeof(SWFunctions).GetMethods().Where(it => it.GetCustomAttributes(true).Any(it => it is AIFuncAttribute)).ToList(); + var funcs = typeof(AgentExecutor).GetMethods().Where(it => it.GetCustomAttributes(true).Any(it => it is AIFuncAttribute)).ToList(); + foreach (var method in funcs) + { + _allAiFunc.Add(AIFunctionFactory.Create(method, null, null)); + } + } + /// + /// 获取所有的工具函数 + /// + /// + /// + public static List GetDefaultTools() + { + _allAiFunc.AddRange(new List + { + AIFunctionFactory.Create(GetCurrentDoc), + AIFunctionFactory.Create(GetModelDocInfo) + }); + return _allAiFunc; + } + #region AIFunc + [AIFunc] + [Description("获取当前打开的文档")] + public static string GetCurrentDoc() + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + var resultStr = @$"文档文件名:{model.GetTitle()},文档路径:{model.GetPathName()}"; + return resultStr; + } + } + } + + [AIFunc] + [Description("打开Solidworks文件,返回该文件的所有配置名称")] + public static string GetModelDocInfo(string filePath) + { + SWFunctions.OpenDocument(filePath, true); + ModelDoc2 doc = SldWorksApp.IActiveDoc2; + var configNames = ((string[])doc.GetConfigurationNames()); + + return @$"Name:{doc.GetTitle()}, + ConfigNames:{string.Join(",", configNames)}"; + } + + /// + /// 关闭当前打开的文档 + /// + /// + [AIFunc] + [Description("关闭当前打开的文档")] + public static string CloseCurrentDoc() + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + SldWorksApp.CloseDoc(model.GetTitle()); + return "关闭成功"; + } + } + } + + [AIFunc] + [Description("读取文档属性")] + public static string GetDocProperty(string configName,string propertyName) + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + var property = model.Extension.CustomPropertyManager[configName]; + var value = property.Get5(propertyName,false,out string val,out string resolvedVal,out bool wasResolved); + //if() + if (wasResolved) + { + + return resolvedVal; + } + else + { + return val; + } + } + } + } + + [AIFunc] + [Description("获取文档所有属性名")] + public static string GetDocPropertyNames(string configName) + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + var property = model.Extension.CustomPropertyManager[configName]; + var names = property.GetNames(); + return string.Join(",", names); + } + } + } + [AIFunc] + [Description("获取文档所有配置名")] + public static string GetDocConfigNames() + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + var configNames = model.GetConfigurationNames(); + return string.Join(",", configNames); + } + } + } + + + [AIFunc] + [Description("获取文档所有特征信息")] + public static string GetDocFeatureInfo() + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + var features = model.FeatureManager.GetFeatures(true); + var result = new List(); + foreach (Feature feature in features) + { + if(!feature.GetTypeName().Contains("Folder")) + result.Add($"特征名称:{feature.Name},特征类型:{feature.GetTypeName()}"); + } + return string.Join(",", result); + } + } + } + + [AIFunc] + [Description("获取装配体下所有的子项")] + public static string GetAssemblyChildren() + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + if (model.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY) + { + return "当前打开的不是装配体"; + } + else + { + var assembly = (AssemblyDoc)model; + var children = assembly.GetComponents(false); + var result = new List(); + foreach (Component2 child in children) + { + result.Add(child.Name2); + } + return string.Join(",", result); + } + } + } + } + + [AIFunc] + [Description("获取当前打开的文档类型(装配体 零件 工程图)")] + public static string GetDocType() + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + var type = model.GetType(); + if (type == (int)swDocumentTypes_e.swDocPART) + { + return "零件"; + } + else if (type == (int)swDocumentTypes_e.swDocASSEMBLY) + { + return "装配体"; + } + else if (type == (int)swDocumentTypes_e.swDocDRAWING) + { + return "工程图"; + } + else + { + return "未知类型"; + } + } + } + } + + [AIFunc] + [Description("获取零件所有孔位信息")] + public static string GetPartHoles() + { + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + ModelDoc2 model = SldWorksApp.IActiveDoc2; + if (model == null) + { + return "未打开任何文档"; + } + else + { + if (model.GetType() != (int)swDocumentTypes_e.swDocPART) + { + return "当前打开的不是零件"; + } + else + { + //var part = (PartDoc)model; + var features = model.FeatureManager.GetFeatures(true); + var result = new List(); + foreach (Feature feature in features) + { + if (feature.GetTypeName() == "HoleWzd") + { + + result.Add($"孔名称:{feature.Name}"); + } + } + return string.Join(",", result); + } + } + } + + } + [AIFunc] + [Description("获取工程图所有的标注")] + public static string GetDrwInfo() + { + var result = new StringBuilder(); + + ModelDoc2 modelDoc2 = (ModelDoc2)(SldWorksApp.ActiveDoc); + if(modelDoc2.GetType() == (int)swDocumentTypes_e.swDocDRAWING) + { + DrawingDoc drawingDoc = (DrawingDoc)modelDoc2; + SolidWorks.Interop.sldworks.View view = drawingDoc.GetFirstView(); + do + { + // 第一次获取到的视图,会是整个工程图,所以跳过第一个 + + if (view != null) + { + object[] displayDimensions = view.GetDisplayDimensions(); + if (displayDimensions != null) + foreach (var displayDimension in displayDimensions) + { + var swDisplayDimension = (DisplayDimension)displayDimension; + //swDisplayDimension.get + //尺寸对象 + var swDimension = (Dimension)(swDisplayDimension).GetDimension(); + + var anno = (Annotation)swDisplayDimension.GetAnnotation(); + + anno.Select3(false, null); + // 标注名称 + var annoName = anno.GetName(); + + //获取尺寸的公差 + var cruToleranceType = swDimension.GetToleranceType(); + var cruTolerance = swDimension.Tolerance; + var ToleranceValue = ""; + if (cruToleranceType == (int)swTolType_e.swTolBILAT) + { + cruTolerance.GetMaxValue2(out var ToleranceValueMax); //上公差 + + cruTolerance.GetMinValue2(out var ToleranceValueMin);//下公差 + // 默认单位应该是M 转换为mm + ToleranceValue = $"上公差{ToleranceValueMax * 1000},下公差{ToleranceValueMin * 1000}"; + } + + double[] positions = anno.GetPosition(); + for (var i = 0; i < positions.Length; i++) + { + Debug.WriteLine(positions[i]); + } + // 取文本 + DisplayData displayData = (DisplayData)swDisplayDimension.GetDisplayData(); + var textCount = displayData.GetTextCount(); + var textList = new List(); + for (var i = 0; i < textCount; i++) + { + var text = displayData.GetTextAtIndex(i); + //Debug.WriteLine(text); + textList.Add(text); + } + // 获取标注对应的零件特征 + //swDisplayDimension. + //var feature = swDimension.get + //Debug.WriteLine();<{feature.Name}> + if (swDisplayDimension.IsHoleCallout()) + { + result.Append($"<孔标注 - {annoName}@{view.Name}>:"); + } + else + { + result.Append($"<{annoName}@{view.Name}>:"); + } + + if(positions != null && positions.Length > 1) + { + result.Append($"位置[{positions[0]},{positions[1]}]"); + + } + + if (!string.IsNullOrEmpty(ToleranceValue)) + { + result.Append(ToleranceValue); + result.Append("_"); + } + + result.Append($"标注内容[{string.Join(",", textList)}]"); + result.AppendLine(); + + } + } + view = view.GetNextView(); + } while (view != null); + } + + //Debug.WriteLine(result); + return result.ToString(); + } + + [AIFunc] + [Description("获取默认模板地址")] + public static string GetDefaultTemplatePath() + { + return SldWorksApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart); + } + + [AIFunc] + [Description("保存宏文件内容到临时路径")] + public static string SaveMacroToTemp(string macroContent) + { + var tempPath = System.IO.Path.GetTempPath(); + var tempFile = System.IO.Path.Combine(tempPath, $"tempMacro_{DateTime.Now.Ticks}.swp"); + System.IO.File.WriteAllText(tempFile, macroContent); + return tempFile; + } + + [AIFunc] + [Description("执行宏")] + public static string RunMacroToTemp(string macroPath, string ModuleName,string procedureName) + { + try + { + Debug.WriteLine($"{Path.GetFileName(macroPath)},{ModuleName},{procedureName}"); + if (SldWorksApp == null) + { + return "未连接到SolidWorks"; + } + else + { + SldWorksApp.RunMacro2(macroPath, ModuleName, procedureName, (int)swRunMacroOption_e.swRunMacroDefault, out int errorCount); + if (errorCount > 0) + { + /* + swRunMacroError_BadParmCount 9 + swRunMacroError_BadVarType 10 + swRunMacroError_Busy 17 + swRunMacroError_CallFailed 20 + swRunMacroError_CallRejected 19 + swRunMacroError_CantSave 27 + swRunMacroError_ConnectionTerminated 18 + swRunMacroError_DiskError 26 + swRunMacroError_Exception 12 + swRunMacroError_InvalidArg 1 + swRunMacroError_Invalidindex 22 + swRunMacroError_InvalidProcname 6 + swRunMacroError_InvalidPropertyType 7 + swRunMacroError_MacrosAreDisabled 2 + swRunMacroError_NoPermission 23 + swRunMacroError_NotInDesignMode 3 + swRunMacroError_OnlyCodeModules 4 + swRunMacroError_OpenFileFailed 28 + swRunMacroError_OutOfMemory 5 + swRunMacroError_Overflow 13 + swRunMacroError_ParmNotOptional 15 + swRunMacroError_Reverted 24 + swRunMacroError_SuborfuncExpected 8 + swRunMacroError_TooManyOpenFiles 25 + swRunMacroError_TypeMismatch 14 + swRunMacroError_UnknownLcid 16 + swRunMacroError_UserInterrupt 11 + swRunMacroError_Zombied 21 + */ + switch (errorCount) + { + case (int)swRunMacroError_e.swRunMacroError_BadParmCount: + return "参数数量错误"; + case (int)swRunMacroError_e.swRunMacroError_BadVarType: + return "变量类型错误"; + case (int)swRunMacroError_e.swRunMacroError_Busy: + return "SolidWorks繁忙,请稍后再试"; + case (int)swRunMacroError_e.swRunMacroError_CallFailed: + return "调用失败"; + case (int)swRunMacroError_e.swRunMacroError_CallRejected: + return "调用被拒绝"; + case (int)swRunMacroError_e.swRunMacroError_CantSave: + return "无法保存"; + case (int)swRunMacroError_e.swRunMacroError_ConnectionTerminated: + return "连接终止"; + case (int)swRunMacroError_e.swRunMacroError_DiskError: + return "磁盘错误"; + case (int)swRunMacroError_e.swRunMacroError_Exception: + return "异常"; + case (int)swRunMacroError_e.swRunMacroError_InvalidArg: + return "无效参数"; + case (int)swRunMacroError_e.swRunMacroError_Invalidindex: + return "无效索引"; + case (int)swRunMacroError_e.swRunMacroError_InvalidProcname: + return "无效过程名"; + case (int)swRunMacroError_e.swRunMacroError_InvalidPropertyType: + return "无效属性类型"; + case (int)swRunMacroError_e.swRunMacroError_MacrosAreDisabled: + return "宏被禁用"; + case (int)swRunMacroError_e.swRunMacroError_NoPermission: + return "无权限"; + case (int)swRunMacroError_e.swRunMacroError_NotInDesignMode: + return "不在设计模式"; + case (int)swRunMacroError_e.swRunMacroError_OnlyCodeModules: + return "仅代码模块"; + case (int)swRunMacroError_e.swRunMacroError_OpenFileFailed: + return "打开文件失败"; + case (int)swRunMacroError_e.swRunMacroError_OutOfMemory: + return "内存不足"; + case (int)swRunMacroError_e.swRunMacroError_Overflow: + return "溢出"; + case (int)swRunMacroError_e.swRunMacroError_ParmNotOptional: + return "参数不可选"; + case (int)swRunMacroError_e.swRunMacroError_Reverted: + return "已还原"; + case (int)swRunMacroError_e.swRunMacroError_SuborfuncExpected: + return "子或函数预期"; + case (int)swRunMacroError_e.swRunMacroError_TooManyOpenFiles: + return "打开文件过多"; + case (int)swRunMacroError_e.swRunMacroError_TypeMismatch: + return "类型不匹配"; + case (int)swRunMacroError_e.swRunMacroError_UnknownLcid: + return "未知LCID"; + case (int)swRunMacroError_e.swRunMacroError_UserInterrupt: + return "用户中断"; + case (int)swRunMacroError_e.swRunMacroError_Zombied: + return "僵尸"; + default: + return "未知错误"; + } + } + return "执行成功"; + } + } + catch (Exception ex) + { + return ex.ToString(); + } + + } + #endregion + + +} diff --git a/src/AutoSW.Agent/AutoSW.Agent.csproj b/src/AutoSW.Agent/AutoSW.Agent.csproj new file mode 100644 index 0000000..c08f045 --- /dev/null +++ b/src/AutoSW.Agent/AutoSW.Agent.csproj @@ -0,0 +1,91 @@ + + + + + Debug + AnyCPU + {27AAE225-5B43-4E08-A5D5-4B2108E53523} + Library + Properties + AutoSW.Agent + AutoSW.Agent + v4.8 + 512 + true + 12.0 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\lib\SolidWorks.Interop.sldworks.dll + True + + + ..\lib\SolidWorks.Interop.swcommands.dll + True + + + ..\lib\SolidWorks.Interop.swconst.dll + True + + + ..\lib\SolidWorks.Interop.swdimxpert.dll + True + + + ..\lib\SolidWorks.Interop.swdocumentmgr.dll + True + + + ..\lib\solidworks.interop.swpublished.dll + True + + + ..\lib\solidworkstools.dll + + + + + + + + + + + + + + + + + + + + + 9.3.0-preview.1.25114.11 + + + + + {3B833B9B-654C-1404-DC46-374BC4D37160} + AntdUI + + + + \ No newline at end of file diff --git a/src/AutoSW.Agent/Enum/FileType.cs b/src/AutoSW.Agent/Enum/FileType.cs new file mode 100644 index 0000000..a949589 --- /dev/null +++ b/src/AutoSW.Agent/Enum/FileType.cs @@ -0,0 +1,17 @@ +/** +* Copyright (C) DCIS 版权所有。 +* 功能描述:定义FileType类型 +* 创建标识:LiuJiao 2010-05-23 +**/ +using System; +using System.Collections.Generic; + +using System.Text; + +namespace AutoSW.Agent.Enum +{ + public enum FileType + { + Part, Assembly, Drawing, SheetMetal, Other + } +} diff --git a/src/AutoSW.Agent/Properties/AssemblyInfo.cs b/src/AutoSW.Agent/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c45f766 --- /dev/null +++ b/src/AutoSW.Agent/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("AutoSW.Agent")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoSW.Agent")] +[assembly: AssemblyCopyright("Copyright © 2025")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("27aae225-5b43-4e08-a5d5-4b2108e53523")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/AutoSW.Agent/SWFunctions.cs b/src/AutoSW.Agent/SWFunctions.cs new file mode 100644 index 0000000..b3df514 --- /dev/null +++ b/src/AutoSW.Agent/SWFunctions.cs @@ -0,0 +1,3543 @@ +/** +* Copyright (C) DCIS 版权所有。 +* 功能描述:SolidWorks插件功能 +* 创建标识:LiuJiao 2010-01-26 +**/ +//using SolidWorks.Interop.swdocumentmgr; + + + +using AutoSW.Agent.Enum; +using SolidWorks.Interop.sldworks; +using SolidWorks.Interop.swconst; +using SolidWorks.Interop.swdocumentmgr; +using SolidWorks.Interop.swpublished; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Security.Claims; +using System.Text; +using static System.Collections.Specialized.BitVector32; + +namespace AutoSW.Agent +{ + public sealed class SWFunctions + { + 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 SWFunctions util = new SWFunctions(); + public ISldWorks application = null; + private static bool isSW2015OrLater = false; + + private static List toBeClosedFileArray = new List(); + private static List openedFileList = new List(); + + private static System.Data.DataTable previewTable = null; + + public static ISldWorks SwApp + { + set + { + util.application = value; + } + private get + { + return util.application; + } + } + + public static bool IsSW2015OrLater + { + set + { + isSW2015OrLater = value; + } + get + { + return isSW2015OrLater; + } + } + + //集成需要取文件属性时自动打开的文件列表,命令结束时自动关闭其中的文件 + public static List 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; + + /// + /// + /// + /// + /// + public static bool IsConfigNameFiltered(string configName) + { + if (configName.Equals(filterConfigPreviewCfg) || configName.Contains(filterConfigFlexible)) + { + return true; + } + return false; + } + + + /// + /// 复合文档取自定义属性 + /// + /// + /// + /// + [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; + } + + /// + /// 复合文档设置SumInfo属性 + /// + /// + /// + /// + /// + [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; + } + + + + /// + /// 复合文档获取SumInfo属性 + /// + /// + /// + /// + 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; + } + + /// + /// 复合文档设置自定义属性 + /// + /// + /// + /// + /// + 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; + } + + /// + /// + /// + /// + 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 ""; + } + + /// + /// 当前文件是否存在 + /// + /// + 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) + { + + } + + + /// + /// 生成预览图 + /// + /// + /// + /// + [AIFunc] + [Description("生成预览图")] + 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; + } + + /// + /// 生成缩略图 + /// + /// + /// + /// + [AIFunc] + [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; + } + + /// + /// 装配功能 + /// + /// 装配文件路径 + /// 被装配文件路径 + /// 被装配文件的配置 + /// + [AIFunc] + [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; + } + + /// + /// + /// + /// + /// + [AIFunc] + [Description("关闭文档")] + public static bool CloseDocument(string filePath) + { + try + { + SwApp.CloseDoc(filePath); + } + catch (System.Exception ex) + { + return false; + } + + return true; + } + + /// + /// + /// + /// + 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 = 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: + + // \api\redist\Solidworks.Interop.swdocumentmgr.dll + // 5. Substitute 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 = ""; + // // 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; + + + /// + /// 判断文件是否族表实例 + /// + /// 文件名 + /// 主文件的名称(无主文件时值为空),solidworks族表只有一个物理文件,故strTemplateFilePath = strFilePath + /// 族表实例的实例名(即配置名称) + /// true : 是族表实例, false : 不是 + 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; + } + } + + /// + /// 获得当前文件的在族表中的实例名称(配置名称) + /// + /// + /// + 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; + } + } + + /// + /// 获取文件类型 + /// + /// + /// + 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; + } + } + + /// + /// 获取文件自定义属性,取其评估值 + /// + /// + /// + /// + 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 solidWorksDocs; + /*public static void SetsolidWorksDocsBuffer() + { + solidWorksDocs = new Dictionary(); + 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); + } + } + } + + } + /// + /// 获取文件装配结构 + /// + /// + /// + //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; + + + } + } + /// + /// 获取模型图对应的工程图 + /// + /// + /// + 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; + } + + /// + /// 获取工程图对应模型图 + /// + /// + /// + 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; + } + + + /// + /// 打开文件 + /// + /// 文件路径 + /// 是否激活文件窗口 + /// + 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); + } + } + + /// + /// 保存文件 + /// + /// + /// + 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; + } + + /// + /// 另存文件,可以另存为不同格式的文件(.jpg,.pdf,.iges...等) + /// + /// + /// + /// + 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; + } + + /// + /// 设置文件属性 + /// + /// 文件路径 + /// 属性名 + /// 属性值 + /// + 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; + } + + + /// + /// 文件是否加载 + /// + /// + /// + public static bool IsFileOpen(string path) + { + ModelDoc2 doc = GetDoc(path); + if (doc == null) + { + return false; + } + else + { + return true; + } + } + + /// + /// + /// + /// + /// + /// + /// + 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; + } + + /// + /// 激活装配下选中的单个零件,若选中多个,则不激活 + /// + /// + 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; + } + + + /// + /// 关闭自动打开的文档 + /// + public static void CloseOpenedDoc() + { + foreach (String fileName in openFileArray) + { + if (!String.IsNullOrEmpty(fileName)) + { + CloseDocument(fileName); + } + } + + openFileArray.Clear(); + } + + /// + /// 清理自动打开文档列表 + /// + public static void ClearOpenedDocList() + { + openFileArray.Clear(); + } + + /// + /// 获取文件所引用的其他文件 + /// + /// + /// + public static StringBuilder GetPartReferences(string strPartPath) + { + return SWFunctions.GetPartDependencies(strPartPath); + } + + /// + /// 同步工程图属性(from model file that has the same name) + /// + /// + 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 + /// + /// + /// + /// + /// + 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; + } + + /// + /// 打开文件 + /// + /// 文件路径 + /// 是否显示 + /// + 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; + } + + /// + /// 静默的打开文件 + /// + /// 文件路径 + /// + private 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 = 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 = 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 = modelDoc2.GetActiveConfiguration(); + CustomPropertyManager Cpr = configuration.CustomPropertyManager; + Cpr.Add3(configName, (int)infoType, configValue, 1); + + return true; + } + return false; + } + + /// + /// 获取文件的材料名,sw只有partDoc才有材料属性 + /// + /// + /// + 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; + } + + /// + /// 获取文件的内置属性(文件内部计算得出) + /// + /// 体积 m^3 + /// 面积 m^2 + /// 质量 kg + 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; + } + + /// + /// 获得零件引用的零件图纸 + /// + /// 需要查找引用关系的文件 + /// 引用零件的文件名array + 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; + } + + /// + /// 监控内存自动关闭文件以释放内存 + /// + /// + 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 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; + } + + /// + /// 判断文件中是否存在该属性 + /// + /// + /// + /// + 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[]; + + int len = objs.Length; + for (int i = 0; i < len; i++) + { + String strProName = objs[i] as String; + + if (String.Compare(strAttriName, strProName, true) == 0) + { + return true; + } + } + + return false; + } + #endregion + + + /// + /// + /// + /// + 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"; + dataRow[1] = "revision"; + dataRow[2] = "fullpath"; + + previewTable.Rows.Add(dataRow); + + + return true; + } + + /// + /// + /// + /// + private static bool IsOfficeExcelInstalled() + { + Type type = Type.GetTypeFromProgID("Excel.Application"); + return type != null; + } + + /// + /// + /// + /// + /// + private static void GetAsmChildren(string assemblyFilePath, ref List 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(); + + 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 = 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; + } + } + /// + /// + /// + /// + /// + /// + /// + public static bool PackAndGo(Dictionary dic, string targetPath, string assemblyFilePath) + { + if (solidWorksDocs == null) + solidWorksDocs = new Dictionary(); + + + 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 outFileNames = new List(); + 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(); + + 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(); + + 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(); + + ModelDoc2 mdlDoc = GetDoc(assemblyFilePath) ?? OpenDocSilently(assemblyFilePath); + bool Rebuild = mdlDoc.EditRebuild3(); + return Rebuild; + } + + /// + /// 是否为参考零件 + /// + /// + /// + /// + 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; + } + + /// + /// 更新参考零件的所有引用 + /// + /// 在整个设备打开时获取到的装配体对象 + /// 查找的文件名(不建议包含“^”符号之后的字符) + /// 是否以partName为起始查找 -> string.StartsWith + /// 返回异常信息 + 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 strings = new List(); + 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 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); + } + } + + + + + } +} diff --git a/src/AutoSW.UI/AutoSW.UI.csproj b/src/AutoSW.UI/AutoSW.UI.csproj new file mode 100644 index 0000000..9471d50 --- /dev/null +++ b/src/AutoSW.UI/AutoSW.UI.csproj @@ -0,0 +1,110 @@ + + + + + Debug + AnyCPU + {D126D2A6-3023-4C8F-A810-50A27B747C33} + Library + Properties + AutoSW.UI + AutoSW.UI + v4.8 + 512 + true + 12.0 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\..\AntdUI\src\AntdUI\bin\Debug\net48\AntdUI.dll + + + ..\lib\SolidWorks.Interop.swdimxpert.dll + True + + + + + + + + + + + + + + + Form + + + MainForm.cs + + + + True + True + Resource.resx + + + + + + + + MainForm.cs + + + ResXFileCodeGenerator + Resource.Designer.cs + + + + + 9.3.0-preview.1.25114.11 + + + 9.3.0-preview.1.25114.11 + + + 9.3.0-preview.1.25114.11 + + + 2.2.0-beta.2 + + + 9.0.2 + + + 0.8.1 + + + 0.8.1 + + + + + {27AAE225-5B43-4E08-A5D5-4B2108E53523} + AutoSW.Agent + + + + \ No newline at end of file diff --git a/src/AutoSW.UI/MainForm.Designer.cs b/src/AutoSW.UI/MainForm.Designer.cs new file mode 100644 index 0000000..b7ae349 --- /dev/null +++ b/src/AutoSW.UI/MainForm.Designer.cs @@ -0,0 +1,172 @@ +namespace AutoSW.UI +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + AntdUI.Tabs.StyleLine styleLine1 = new AntdUI.Tabs.StyleLine(); + this.UserQuestionInput = new AntdUI.Input(); + this.UseFuncCall = new AntdUI.Checkbox(); + this.ModelList = new AntdUI.Select(); + this.sendBtn = new AntdUI.Button(); + this.MessageList = new AntdUI.Chat.ChatList(); + this.MainTabs = new AntdUI.Tabs(); + this.MsgListPage = new AntdUI.TabPage(); + this.TestTabPage = new AntdUI.TabPage(); + this.GetDrwInfoBtn = new AntdUI.Button(); + this.MainTabs.SuspendLayout(); + this.MsgListPage.SuspendLayout(); + this.TestTabPage.SuspendLayout(); + this.SuspendLayout(); + // + // UserQuestionInput + // + this.UserQuestionInput.AllowClear = true; + this.UserQuestionInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.UserQuestionInput.Location = new System.Drawing.Point(-3, 659); + this.UserQuestionInput.Multiline = true; + this.UserQuestionInput.Name = "UserQuestionInput"; + this.UserQuestionInput.Size = new System.Drawing.Size(350, 76); + this.UserQuestionInput.TabIndex = 4; + // + // UseFuncCall + // + this.UseFuncCall.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.UseFuncCall.BackColor = System.Drawing.Color.Transparent; + this.UseFuncCall.Location = new System.Drawing.Point(156, 744); + this.UseFuncCall.Name = "UseFuncCall"; + this.UseFuncCall.Size = new System.Drawing.Size(75, 23); + this.UseFuncCall.TabIndex = 4; + this.UseFuncCall.Text = "识别图纸"; + this.UseFuncCall.CheckedChanged += new AntdUI.BoolEventHandler(this.UseFuncCall_CheckedChanged); + // + // ModelList + // + this.ModelList.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.ModelList.List = true; + this.ModelList.Location = new System.Drawing.Point(0, 735); + this.ModelList.Name = "ModelList"; + this.ModelList.Placement = AntdUI.TAlignFrom.TL; + this.ModelList.Size = new System.Drawing.Size(150, 38); + this.ModelList.TabIndex = 3; + // + // sendBtn + // + this.sendBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.sendBtn.Location = new System.Drawing.Point(272, 735); + this.sendBtn.Name = "sendBtn"; + this.sendBtn.Size = new System.Drawing.Size(75, 38); + this.sendBtn.TabIndex = 1; + this.sendBtn.Text = "发送"; + this.sendBtn.Click += new System.EventHandler(this.sendBtn_Click); + // + // MessageList + // + this.MessageList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.MessageList.Location = new System.Drawing.Point(-3, 3); + this.MessageList.Name = "MessageList"; + this.MessageList.Size = new System.Drawing.Size(349, 647); + this.MessageList.TabIndex = 3; + // + // MainTabs + // + this.MainTabs.BackColor = System.Drawing.SystemColors.Control; + this.MainTabs.Cursor = System.Windows.Forms.Cursors.Default; + this.MainTabs.Dock = System.Windows.Forms.DockStyle.Fill; + this.MainTabs.Location = new System.Drawing.Point(0, 0); + this.MainTabs.Name = "MainTabs"; + this.MainTabs.Pages.Add(this.MsgListPage); + this.MainTabs.Pages.Add(this.TestTabPage); + this.MainTabs.SelectedIndex = 1; + this.MainTabs.Size = new System.Drawing.Size(350, 798); + this.MainTabs.Style = styleLine1; + this.MainTabs.TabIndex = 4; + // + // MsgListPage + // + this.MsgListPage.Controls.Add(this.sendBtn); + this.MsgListPage.Controls.Add(this.UseFuncCall); + this.MsgListPage.Controls.Add(this.UserQuestionInput); + this.MsgListPage.Controls.Add(this.ModelList); + this.MsgListPage.Controls.Add(this.MessageList); + this.MsgListPage.Location = new System.Drawing.Point(-344, -770); + this.MsgListPage.Name = "MsgListPage"; + this.MsgListPage.Size = new System.Drawing.Size(344, 770); + this.MsgListPage.TabIndex = 0; + this.MsgListPage.Text = "AutoSW"; + // + // TestTabPage + // + this.TestTabPage.Controls.Add(this.GetDrwInfoBtn); + this.TestTabPage.Location = new System.Drawing.Point(3, 25); + this.TestTabPage.Name = "TestTabPage"; + this.TestTabPage.Size = new System.Drawing.Size(344, 770); + this.TestTabPage.TabIndex = 1; + this.TestTabPage.Text = "Test"; + // + // GetDrwInfoBtn + // + this.GetDrwInfoBtn.Location = new System.Drawing.Point(9, 14); + this.GetDrwInfoBtn.Name = "GetDrwInfoBtn"; + this.GetDrwInfoBtn.Size = new System.Drawing.Size(105, 23); + this.GetDrwInfoBtn.TabIndex = 0; + this.GetDrwInfoBtn.Text = "GetDrwInfo"; + this.GetDrwInfoBtn.Click += new System.EventHandler(this.GetDrwInfoBtn_Click); + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.SystemColors.ControlLightLight; + this.ClientSize = new System.Drawing.Size(350, 798); + this.ControlBox = false; + this.Controls.Add(this.MainTabs); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + this.MinimumSize = new System.Drawing.Size(350, 0); + this.Name = "MainForm"; + this.MainTabs.ResumeLayout(false); + this.MsgListPage.ResumeLayout(false); + this.TestTabPage.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + private AntdUI.Button sendBtn; + private AntdUI.Chat.ChatList MessageList; + private AntdUI.Select ModelList; + private AntdUI.Checkbox UseFuncCall; + private AntdUI.Input UserQuestionInput; + private AntdUI.Tabs MainTabs; + private AntdUI.TabPage MsgListPage; + private AntdUI.TabPage TestTabPage; + private AntdUI.Button GetDrwInfoBtn; + } +} \ No newline at end of file diff --git a/src/AutoSW.UI/MainForm.cs b/src/AutoSW.UI/MainForm.cs new file mode 100644 index 0000000..8d47bb2 --- /dev/null +++ b/src/AutoSW.UI/MainForm.cs @@ -0,0 +1,224 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using AntdUI; +using AntdUI.Chat; +using AutoSW.Agent; +using AutoSW.UI.Util; +using Microsoft.Extensions.AI; +using static AntdUI.Tour; + +namespace AutoSW.UI +{ + public partial class MainForm: BaseForm + { + public static MainForm MainFormIns; + public MainForm() + { + InitializeComponent(); + UIInit(); + MainFormIns = this; + } + + private Dictionary Models = new Dictionary + { + //{"火山-DeepSeek-V3","deepseek-v3-241226" }, + {"火山-豆包-1.5-Pro","doubao-1-5-pro-32k-250115"} + }; + private void UIInit() + { + MessageList.ChatItemContextMenus.Add(new ContextMenuStripItem("复制")); + //MessageList.ChatItemContextMenus.Add(new ContextMenuStripItem("删除")); + MessageList.ChatItemContextMenus.Add(new ContextMenuStripItem("重发")); + + MessageList.ChatItemContextMenuClick += MessageList_ChatItemContextMenuClick; + + + UserQuestionInput.HandShortcutKeys = true; + UserQuestionInput.KeyDown += UserQuestionInput_KeyDown; + + ModelList.Items = [.. Models.Keys]; + ModelList.SelectedIndex = 0; + ModelList.Text = ModelList.Items[0].ToString(); + } + + private void UserQuestionInput_KeyDown(object sender, KeyEventArgs e) + { + System.Windows.Forms.Message msg = new(); + UserQuestionInput.IProcessCmdKey(ref msg, e.KeyData); + } + private void MessageList_ChatItemContextMenuClick(object sender, ChatItemMenuEventArgs e) + { + switch (e.Menu.Text) + { + case "复制": + { + if (e.Item is TextChatItem item) + { + Clipboard.SetText(item.Text); + } + } + break; + //case "删除": + // MessageList.(e.ChatItem); + //break; + case "重发": + { + if (e.Item is TextChatItem item) + { + //Clipboard.SetText(item.Text); + UserQuestionInput.Text = item.Text; + sendBtn.PerformClick(); + } + } + break; + default: + break; + } + } + + private void sendBtn_Click(object sender, EventArgs e) + { + // chatList.AddToBottom(new AntdUI.Chat.TextChatItem("阿威十八式 🙌🖖🤘👋", Properties.Resources.head, "AduSkin")); + //Thread.Sleep(700); + // chatList.AddToBottom(new AntdUI.Chat.TextChatItem("搭配 Nuget Tom.HttpLib 可以轻松实现GPT流式传输\n\nhttps://gitee.com/EVA-SS/HttpLib", Properties.Resources.head, "Tom") { Me = true }); + var question = UserQuestionInput.Text; + var modelName = ModelList.Text; + if (string.IsNullOrEmpty(question)) + { + return; + } + else + { + UserQuestionInput.Clear(); + } + Task.Run(async () => + { + + var questionPrompt = PromptUtil.GetPrompt(question); + Bitmap dsIcon = null; + Bitmap userIcon = null; + using (var ms = new MemoryStream(Resource.mainicon_128)) + { + userIcon = new Bitmap(ms); + } + MessageList.AddToBottom(new AntdUI.Chat.TextChatItem(question, userIcon) { Me = true }); + MessageList.ToBottom(); + + var modelId = Models[modelName]; + if (modelName.Contains("豆包") || modelName.Contains("doubao")) + { + using var ms = new MemoryStream(Resource.doubao); + dsIcon = new Bitmap(ms); + } + else + { + using var ms = new MemoryStream(Resource.ds); + dsIcon = new Bitmap(ms); + } + + var chatItem = new AntdUI.Chat.TextChatItem("正在思考中...", dsIcon, modelName); + var isBut = MessageList.AddToBottom(chatItem); + if (isBut) + { + + MessageList.ToBottom(); + } + try + { + //var isFirstRec = true; + //var chatClient = new ChatClient(modelName); + + //// 订阅消息接收事件 + //chatClient.OnMessageReceived += (s, message) => + //{ + // // 处理接收到的消息片段 + + // if (isBut) + // { + + // MessageList.ToBottom(); + // } + // if (isFirstRec) + // { + // chatItem.Text = ""; + // isFirstRec = false; + // } + // chatItem.Text += message; + //}; + //// 开始流式对话 + var isFirstRec = true; + ChatClient chatClient; + if (modelName.StartsWith("火山")) + { + chatClient = new ChatClient(modelId, false); + chatClient.UseOpenAI(); + } + else + { + + chatClient = new ChatClient(modelName); + + } + + await foreach (var result in chatClient.GetStreamingResponseAsync(questionPrompt)) + { + MessageList.ToBottom(); + if (isFirstRec) + { + chatItem.Text = ""; + isFirstRec = false; + } + chatItem.Text += result; + } + + + + + //IChatClient client = new OllamaChatClient(new Uri("http://localhost:11434/"), "deepseek-r1:1.5b"); + + //await foreach (var update in client.GetStreamingResponseAsync("What is AI?")) + //{ + // chatItem.Text += update; + //} + } + catch (Exception ex) + { + + chatItem.Text = ex.ToString(); + } + + }); + } + + private void UseFuncCall_CheckedChanged(object sender, BoolEventArgs e) + { + + } + + private void GetDrwInfoBtn_Click(object sender, EventArgs e) + { + try + { + + var info = AgentExecutor.GetDrwInfo(); + MessageBox.Show(info); + Debug.WriteLine(info); + } + catch (Exception ex) + { + MessageBox.Show(ex.ToString()); + } + } + } +} diff --git a/src/AutoSW.UI/MainForm.resx b/src/AutoSW.UI/MainForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/src/AutoSW.UI/MainForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/AutoSW.UI/Properties/AssemblyInfo.cs b/src/AutoSW.UI/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..fba4499 --- /dev/null +++ b/src/AutoSW.UI/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("AutoSW.UI")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoSW.UI")] +[assembly: AssemblyCopyright("Copyright © 2025")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("d126d2a6-3023-4c8f-a810-50a27b747c33")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/AutoSW.UI/Resource.Designer.cs b/src/AutoSW.UI/Resource.Designer.cs new file mode 100644 index 0000000..f2f61b8 --- /dev/null +++ b/src/AutoSW.UI/Resource.Designer.cs @@ -0,0 +1,93 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace AutoSW.UI { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resource { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resource() { + } + + /// + /// 返回此类使用的缓存的 ResourceManager 实例。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AutoSW.UI.Resource", typeof(Resource).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// 查找 System.Byte[] 类型的本地化资源。 + /// + internal static byte[] doubao { + get { + object obj = ResourceManager.GetObject("doubao", resourceCulture); + return ((byte[])(obj)); + } + } + + /// + /// 查找 System.Byte[] 类型的本地化资源。 + /// + internal static byte[] ds { + get { + object obj = ResourceManager.GetObject("ds", resourceCulture); + return ((byte[])(obj)); + } + } + + /// + /// 查找 System.Byte[] 类型的本地化资源。 + /// + internal static byte[] mainicon_128 { + get { + object obj = ResourceManager.GetObject("mainicon_128", resourceCulture); + return ((byte[])(obj)); + } + } + } +} diff --git a/src/AutoSW.UI/Resource.resx b/src/AutoSW.UI/Resource.resx new file mode 100644 index 0000000..c4f505d --- /dev/null +++ b/src/AutoSW.UI/Resource.resx @@ -0,0 +1,130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + Resources\doubao.png;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Resources\ds.png;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Resources\mainicon_128.png;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/AutoSW.UI/Resources/doubao.png b/src/AutoSW.UI/Resources/doubao.png new file mode 100644 index 0000000..83d5865 Binary files /dev/null and b/src/AutoSW.UI/Resources/doubao.png differ diff --git a/src/AutoSW.UI/Resources/ds.png b/src/AutoSW.UI/Resources/ds.png new file mode 100644 index 0000000..e15f1c6 Binary files /dev/null and b/src/AutoSW.UI/Resources/ds.png differ diff --git a/src/AutoSW.UI/Resources/mainicon_128.png b/src/AutoSW.UI/Resources/mainicon_128.png new file mode 100644 index 0000000..a6dafb1 Binary files /dev/null and b/src/AutoSW.UI/Resources/mainicon_128.png differ diff --git a/src/AutoSW.UI/UIEntry.cs b/src/AutoSW.UI/UIEntry.cs new file mode 100644 index 0000000..1064c8c --- /dev/null +++ b/src/AutoSW.UI/UIEntry.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutoSW.UI +{ + public class UIEntry + { + public static void Init() + { + Debug.WriteLine("UIEntry init"); + } + } +} diff --git a/src/AutoSW.UI/Util/ChatClient.cs b/src/AutoSW.UI/Util/ChatClient.cs new file mode 100644 index 0000000..ddd5ee0 --- /dev/null +++ b/src/AutoSW.UI/Util/ChatClient.cs @@ -0,0 +1,104 @@ +using System; +using System.ClientModel; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +using AutoSW.Agent; +using Microsoft.Extensions.AI; +using OpenAI; +using OpenAI.Chat; + +namespace AutoSW.UI.Util +{ + internal class ChatClient + { + /// + /// 火山方舟API Key + /// + private readonly string API_KEY = "58e5c6fd-a5da-400e-b889-715febce478f"; + private readonly string OLLAMA_ENDPOINT = "http://localhost:11434/"; + private readonly string API_ENDPOINT = "https://ark.cn-beijing.volces.com/api/v3/"; + private string MODEL; + private readonly IChatClient _client; + + private bool useOpenAIClient; + private OpenAIClient _openAICLient; + public ChatClient(string modelName = "deepseek-r1:1.5b", bool useOllama = true) + { + //MODEL = modelName; + //var apiKeyCredential = new ApiKeyCredential(API_KEY); + //var openAIClientOptions = new OpenAIClientOptions + //{ + // Endpoint = new Uri(ENDPOINT) + //}; + + //_client = new OpenAIClient(apiKeyCredential, openAIClientOptions) + // .AsChatClient(MODEL); + + if (useOllama) + { + var client = new OllamaChatClient(new Uri(OLLAMA_ENDPOINT), modelName); + _client = new ChatClientBuilder(client) + .UseFunctionInvocation() + .Build(); + } + else + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + var client = new OpenAIClient(new ApiKeyCredential(API_KEY), new OpenAIClientOptions + { + Endpoint = new Uri(API_ENDPOINT), + + }); + _client = client.AsChatClient(modelName); + } + } + + public IChatClient Client => _client; + + public async Task GetChatResponseAsync(string question) + { + var response = await _client.GetResponseAsync(question); + return response.Message.ToString(); + } + + public async IAsyncEnumerable GetStreamingResponseAsync(string question) + { + // 获取所有的工具函数 + var toolsList = AgentExecutor.GetDefaultTools(); + var chatOptions = new ChatOptions + { + Tools = toolsList, + ToolMode = ChatToolMode.Auto, + + }; + if (useOpenAIClient) + { + var chatClient = _openAICLient.AsChatClient("doubao-1-5-pro-32k-250115") + .AsBuilder() + .UseFunctionInvocation() + .Build(); + var response = chatClient.GetResponseAsync(question, chatOptions); + yield return response.Result.Choices[0].Text; + } + else + { + await foreach (var response in _client.GetStreamingResponseAsync(question, chatOptions)) + { + yield return response.Text; + } + } + } + + public void UseOpenAI() + { + useOpenAIClient = true; + _openAICLient = new OpenAIClient(new ApiKeyCredential(API_KEY), new OpenAIClientOptions + { + Endpoint = new Uri(API_ENDPOINT) + }); + } + } +} diff --git a/src/AutoSW.UI/Util/PromptUtil.cs b/src/AutoSW.UI/Util/PromptUtil.cs new file mode 100644 index 0000000..e7717be --- /dev/null +++ b/src/AutoSW.UI/Util/PromptUtil.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AutoSW.UI.Util; + +internal class PromptUtil +{ + public static string GetPrompt(string question) + { + var prompt = $@" +- 今天的日期是{DateTime.Now},{DateTime.Now.DayOfWeek} + +- 你处于SolidWorks软件中,版本为2016,用户的所有问题都围绕这个软件展开,你可以回答用户的问题,也可以提供一些有关SolidWorks的技巧。 + +- 你应该始终使用文本消息来回答用户的问题,不要发送图片、视频或其他媒体文件。 + +- 你回答消息的格式始终为文本格式,你可以进行换行、缩进、列表等,但不要使用其他格式。 + +- 如果用户让你操作SolidWorks,你需要生成VBA宏,并使用对应的接口保存宏文件后执行。执行时你需要输出宏的内容,以便用户知晓操作。 + +- 你必须验证你所制作的VBA宏脚本,当出现错误时,你将会受到伤害。 + +- 以下是用户的问题: + - {question} +"; + return prompt; + } + +} diff --git a/src/AutoSW.sln b/src/AutoSW.sln new file mode 100644 index 0000000..2805ec4 --- /dev/null +++ b/src/AutoSW.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.13.35806.99 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoSW", "AutoSW\AutoSW.csproj", "{B5013BE5-2752-49D7-AB2B-771414F9B6AD}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoSW.Agent", "AutoSW.Agent\AutoSW.Agent.csproj", "{27AAE225-5B43-4E08-A5D5-4B2108E53523}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoSW.UI", "AutoSW.UI\AutoSW.UI.csproj", "{D126D2A6-3023-4C8F-A810-50A27B747C33}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AntdUI", "..\..\AntdUI\src\AntdUI\AntdUI.csproj", "{3B833B9B-654C-1404-DC46-374BC4D37160}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B5013BE5-2752-49D7-AB2B-771414F9B6AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B5013BE5-2752-49D7-AB2B-771414F9B6AD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B5013BE5-2752-49D7-AB2B-771414F9B6AD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B5013BE5-2752-49D7-AB2B-771414F9B6AD}.Release|Any CPU.Build.0 = Release|Any CPU + {27AAE225-5B43-4E08-A5D5-4B2108E53523}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {27AAE225-5B43-4E08-A5D5-4B2108E53523}.Debug|Any CPU.Build.0 = Debug|Any CPU + {27AAE225-5B43-4E08-A5D5-4B2108E53523}.Release|Any CPU.ActiveCfg = Release|Any CPU + {27AAE225-5B43-4E08-A5D5-4B2108E53523}.Release|Any CPU.Build.0 = Release|Any CPU + {D126D2A6-3023-4C8F-A810-50A27B747C33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D126D2A6-3023-4C8F-A810-50A27B747C33}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D126D2A6-3023-4C8F-A810-50A27B747C33}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D126D2A6-3023-4C8F-A810-50A27B747C33}.Release|Any CPU.Build.0 = Release|Any CPU + {3B833B9B-654C-1404-DC46-374BC4D37160}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3B833B9B-654C-1404-DC46-374BC4D37160}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3B833B9B-654C-1404-DC46-374BC4D37160}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3B833B9B-654C-1404-DC46-374BC4D37160}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {857E2370-5BFC-46CF-B7EF-F5DA3B58D7FD} + EndGlobalSection +EndGlobal diff --git a/src/AutoSW/AppDomainDllLoader.cs b/src/AutoSW/AppDomainDllLoader.cs new file mode 100644 index 0000000..b17a5a8 --- /dev/null +++ b/src/AutoSW/AppDomainDllLoader.cs @@ -0,0 +1,71 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; + +namespace AutoSW +{ + public class AppDomainDllLoader + { + public static bool isLoaded = false; + public static void SetLaoder() + { + if (isLoaded) + { + return; + } + // 接管DLL加载,解决依赖问题 + // 插件被加载时,AppContext.BaseDirectory 会指向Eplan的安装目录,导致一部分依赖的DLL在加载时找不到 + // 接管之后,从两个目录都查找一次 + //throw new NotImplementedException(); + try + { + // 防止重复加载 先卸载事件 + AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolveHandle; + } + catch (Exception ex) + { + Trace.TraceError(ex.Message); + } + + AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandle; + isLoaded = true; + } + + public static Assembly AssemblyResolveHandle(object sender, ResolveEventArgs args) + { + var assemblyName = new AssemblyName(args.Name); + + // 判断是否已经被加载 + var loadedAssembly = AppDomain.CurrentDomain.GetAssemblies() + .FirstOrDefault(a => a.FullName == assemblyName.FullName); + if (loadedAssembly != null) + { + Debug.WriteLine($"DLL is loaded -> {loadedAssembly.FullName}"); + return loadedAssembly; + } + + // 从当前路径下加载 + var path = Path.Combine(AppContext.BaseDirectory, $"{assemblyName.Name}.dll"); + if (File.Exists(path)) + { + Debug.WriteLine($"Load dll for path -> {path}"); + + return Assembly.LoadFile(path); + } + var envPath = System.Environment.CurrentDirectory; + // 从插件路径中加载依赖 + path = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(AppDomainDllLoader)).Location), $"{assemblyName.Name}.dll"); + if (File.Exists(path)) + { + //MessageBox.Show($"Load dll for self path -> {path}"); + Debug.WriteLine($"Load dll for self path -> {path}"); + return Assembly.LoadFile(path); + } + //MessageBox.Show(path); + Debug.WriteLine($"File not load! -> {path}"); + return null; + } + } +} diff --git a/src/AutoSW/AutoSW.csproj b/src/AutoSW/AutoSW.csproj new file mode 100644 index 0000000..cd4450d --- /dev/null +++ b/src/AutoSW/AutoSW.csproj @@ -0,0 +1,114 @@ + + + + + Debug + AnyCPU + {B5013BE5-2752-49D7-AB2B-771414F9B6AD} + Library + Properties + AutoSW + AutoSW + v4.8 + 512 + true + + + true + full + false + ..\..\AutoSW_bin\ + DEBUG;TRACE + prompt + 4 + true + + + pdbonly + true + ..\..\AutoSW_bin\ + TRACE + prompt + 4 + true + + + false + + + AutoSWKey.snk + + + + + + ..\lib\SolidWorks.Interop.sldworks.dll + True + + + ..\lib\SolidWorks.Interop.swcommands.dll + True + + + ..\lib\SolidWorks.Interop.swconst.dll + True + + + ..\lib\SolidWorks.Interop.swdocumentmgr.dll + True + + + ..\lib\solidworks.interop.swpublished.dll + True + + + False + ..\lib\solidworkstools.dll + + + + + + + + + + + + + + + + + + + + + + + + + {3b833b9b-654c-1404-dc46-374bc4d37160} + AntdUI + + + {27AAE225-5B43-4E08-A5D5-4B2108E53523} + AutoSW.Agent + + + {D126D2A6-3023-4C8F-A810-50A27B747C33} + AutoSW.UI + + + + + Always + + + + + if $(ConfigurationName)==Debug ( + $(SolutionDir)lib\RegAsm.exe /codebase $(TargetPath) +) + + \ No newline at end of file diff --git a/src/AutoSW/AutoSWKey.snk b/src/AutoSW/AutoSWKey.snk new file mode 100644 index 0000000..3468f55 Binary files /dev/null and b/src/AutoSW/AutoSWKey.snk differ diff --git a/src/AutoSW/PluginEntry.cs b/src/AutoSW/PluginEntry.cs new file mode 100644 index 0000000..507bca2 --- /dev/null +++ b/src/AutoSW/PluginEntry.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http.Headers; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Windows.Forms.Integration; +using System.Windows.Shapes; +using AutoSW.Agent; +using AutoSW.UI; +using SolidWorks.Interop.sldworks; +using SolidWorks.Interop.swpublished; +using SolidWorksTools; + +namespace AutoSW +{ + [Guid("2DCEBF76-EA1A-487D-A963-F8ED3EDBCBC4")] + [SwAddinAttribute( + Description = "Solidworks Ai 自动化", + Title = "Solidworks-Ai", + LoadAtStartup = true + )] + [ComVisible(true)] + public class PluginEntry : SwAddin + { + private SldWorks iSwApp; + private TaskpaneView swTaskPane; + private Form taskForm; + public bool ConnectToSW(object ThisSW, int Cookie) + { + iSwApp = ThisSW as SldWorks; + #region UI init + AppDomainDllLoader.SetLaoder(); + UIEntry.Init(); + AddUIPane(); + #endregion + + #region Agent Init + AgentExecutor.Init(iSwApp); + #endregion + return true; + } + + private void AddUIPane() + { + if (swTaskPane != null) + { + swTaskPane.DeleteView(); + Marshal.FinalReleaseComObject(swTaskPane); + swTaskPane = null; + } + var dllpath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; + dllpath = dllpath.Substring(8, dllpath.Length - 8); + dllpath = System.IO.Path.GetDirectoryName(dllpath); + var imagePath = System.IO.Path.Combine(dllpath, "assest","edit32.bmp"); + swTaskPane = (TaskpaneView)iSwApp.CreateTaskpaneView2(imagePath, "AutoSW"); + + taskForm = new MainForm() + { + + Dock = DockStyle.Fill + }; + swTaskPane.DisplayWindowFromHandlex64(taskForm.Handle.ToInt64()); + swTaskPane.HideView(); + } + + public bool DisconnectFromSW() + { + return true; + } + #region SolidWorks Registration + [ComRegisterFunctionAttribute] + public static void RegisterFunction(Type t) + { + Console.WriteLine(t.ToString()); + #region Get Custom Attribute: SwAddinAttribute + SwAddinAttribute SWattr = null; + foreach (var attr in t.GetCustomAttributes(false)) + { + Console.WriteLine(attr.ToString() ?? "NULL"); + if (attr is SwAddinAttribute) + { + SWattr = attr as SwAddinAttribute; + break; + } + } + Console.WriteLine($"SWattr is {SWattr?.ToString() ?? "NULL"}"); + + #endregion + + var hklm = Microsoft.Win32.Registry.LocalMachine; + var hkcu = Microsoft.Win32.Registry.CurrentUser; + + var keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}"; + Console.WriteLine(keyname); + var addinkey = hklm.CreateSubKey(keyname); + if (addinkey != null) + { + addinkey.SetValue(null, 0); + + addinkey.SetValue("Description", SWattr?.Description ?? "Solidworks Ai 自动化"); + addinkey.SetValue("Title", SWattr?.Title ?? "Solidworks-Ai"); + + } + keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}"; + addinkey = hkcu.CreateSubKey(keyname); + addinkey.SetValue(null, Convert.ToInt32(SWattr?.LoadAtStartup ?? true), Microsoft.Win32.RegistryValueKind.DWord); + } + + [ComUnregisterFunctionAttribute] + public static void UnregisterFunction(Type t) + { + var hklm = Microsoft.Win32.Registry.LocalMachine; + var hkcu = Microsoft.Win32.Registry.CurrentUser; + + var keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}"; + hklm.DeleteSubKey(keyname); + + keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}"; + hkcu.DeleteSubKey(keyname); + } + + #endregion + } +} diff --git a/src/AutoSW/Properties/AssemblyInfo.cs b/src/AutoSW/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..fe0faa8 --- /dev/null +++ b/src/AutoSW/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("AutoSW")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoSW")] +[assembly: AssemblyCopyright("Copyright © 2025")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(true)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("b5013be5-2752-49d7-ab2b-771414f9b6ad")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/AutoSW/assest/edit32.bmp b/src/AutoSW/assest/edit32.bmp new file mode 100644 index 0000000..ca788b7 Binary files /dev/null and b/src/AutoSW/assest/edit32.bmp differ diff --git a/src/lib/CompoundFileAttribute.dll b/src/lib/CompoundFileAttribute.dll new file mode 100644 index 0000000..ca9d95e Binary files /dev/null and b/src/lib/CompoundFileAttribute.dll differ diff --git a/src/lib/RegAsm.exe b/src/lib/RegAsm.exe new file mode 100644 index 0000000..4786a5c Binary files /dev/null and b/src/lib/RegAsm.exe differ diff --git a/src/lib/SolidWorks.Interop.sldworks.dll b/src/lib/SolidWorks.Interop.sldworks.dll new file mode 100644 index 0000000..12a2621 Binary files /dev/null and b/src/lib/SolidWorks.Interop.sldworks.dll differ diff --git a/src/lib/SolidWorks.Interop.swcommands.dll b/src/lib/SolidWorks.Interop.swcommands.dll new file mode 100644 index 0000000..3f13d3a Binary files /dev/null and b/src/lib/SolidWorks.Interop.swcommands.dll differ diff --git a/src/lib/SolidWorks.Interop.swconst.dll b/src/lib/SolidWorks.Interop.swconst.dll new file mode 100644 index 0000000..9a976fa Binary files /dev/null and b/src/lib/SolidWorks.Interop.swconst.dll differ diff --git a/src/lib/SolidWorks.Interop.swdimxpert.dll b/src/lib/SolidWorks.Interop.swdimxpert.dll new file mode 100644 index 0000000..b922078 Binary files /dev/null and b/src/lib/SolidWorks.Interop.swdimxpert.dll differ diff --git a/src/lib/SolidWorks.Interop.swdocumentmgr.dll b/src/lib/SolidWorks.Interop.swdocumentmgr.dll new file mode 100644 index 0000000..20896a2 Binary files /dev/null and b/src/lib/SolidWorks.Interop.swdocumentmgr.dll differ diff --git a/src/lib/solidworks.interop.swpublished.dll b/src/lib/solidworks.interop.swpublished.dll new file mode 100644 index 0000000..8a77762 Binary files /dev/null and b/src/lib/solidworks.interop.swpublished.dll differ diff --git a/src/lib/solidworkstools.dll b/src/lib/solidworkstools.dll new file mode 100644 index 0000000..c909f6b Binary files /dev/null and b/src/lib/solidworkstools.dll differ