文章目录
一、更新日志
2020-10-19
2020-11-16
略微细化介绍,补充部分代码
Ⅰ、开发DLL环境
一、 第一步安装SolidWorks API SDK.msi
在SW软件里找到SolidWorks API SDK.msi
不过我这里有2014的
提取码:1123
二、 第二步得到SW开发文档"API"获取模版
可以用一些方式从SolidWorks API SDK.msi中得到
不过我这里有2014的,放到指定路径就能直接使用
安装地址参考
提取码:1123
三、 第三步找到需要引用的DLL文件
总之我这里有2014的
提取码:1123
Ⅱ、使用
一、获取SW文件支撑的版本代号
1.调用的方法体
我这个写在SwAddin.cs内
/// <summary>
/// 得到文件路径文件支持的版本代号
/// </summary>
/// <param name="Path">文件路径</param>
/// <returns></returns>
public static string VersionIdentify(string Path)
{
try
{
ModelDoc2 Part = default(ModelDoc2);
Part = (ModelDoc2)iSwApp.ActiveDoc;
string[] VersionMessage = iSwApp.VersionHistory(Path);
string[] ObtainVersion = new string[VersionMessage.Length];
for (int i = 0; i < VersionMessage.Length; i++)
{
string[] Obtain = VersionMessage[i].ToString().Split(new char[] { '[' });
string VersionCode = Obtain[0];
//转成自编代号
ObtainVersion[i] = Versions(VersionCode);
}
string Version = "";
int j = 1;
Version = ObtainVersion[0].ToString();
for (int i = 1; i < ObtainVersion.Length; i++)
{
if (ObtainVersion[i] != null)
{
//当前文件支持版本
Version += "," + ObtainVersion[i];
j++;
}
}
return Version;
}
catch (Exception ex)
{
return "0";
}
}
*
/// <summary>
/// 返回自编的版本代号
/// </summary>
/// <param name="Version">本身获取的版本代号</param>
/// <returns></returns>
public static string Versions(string Version)
{
switch (Version)
{
case "44":
return "0";
MessageBox.Show("SOLIDWORKS 95");
break;
case "243":
return "1";
MessageBox.Show("SOLIDWORKS 96");
break;
case "483":
return "2";
MessageBox.Show("SOLIDWORKS 97");
break;
case "629":
return "3";
MessageBox.Show("SOLIDWORKS 97Plus");
break;
case "822":
return "4";
MessageBox.Show("SOLIDWORKS 98");
break;
case "1008":
return "5";
MessageBox.Show("SOLIDWORKS 98Plus");
break;
case "1137":
return "6";
MessageBox.Show("SOLIDWORKS 99");
break;
case "1500":
return "7";
MessageBox.Show("SOLIDWORKS 2000");
break;
case "1750":
return "8";
MessageBox.Show("SOLIDWORKS 2001");
break;
case "1950":
return "9";
MessageBox.Show("SOLIDWORKS 2001Plus");
break;
case "2200":
return "10";
MessageBox.Show("SOLIDWORKS 2003");
break;
case "2500":
return "11";
MessageBox.Show("SOLIDWORKS 2004");
break;
case "2800":
return "12";
MessageBox.Show("SOLIDWORKS 2005");
break;
case "3100":
return "13";
MessageBox.Show("SOLIDWORKS 2006");
break;
case "3400":
return "14";
MessageBox.Show("SOLIDWORKS 2007");
break;
case "3800":
return "15";
MessageBox.Show("SOLIDWORKS 2008");
break;
case "4100":
return "16";
MessageBox.Show("SOLIDWORKS 2009");
break;
case "4400":
return "17";
MessageBox.Show("SOLIDWORKS 2010");
break;
case "4700":
return "18";
MessageBox.Show("SOLIDWORKS 2011");
break;
case "5000":
return "19";
MessageBox.Show("SOLIDWORKS 2012");
break;
case "6000":
return "20";
MessageBox.Show("SOLIDWORKS 2013");
break;
case "7000":
return "21";
MessageBox.Show("SOLIDWORKS 2014");
break;
case "8000":
return "22";
MessageBox.Show("SOLIDWORKS 2015");
break;
case "9000":
return "23";
MessageBox.Show("SOLIDWORKS 2016");
break;
case "10000":
return "24";
MessageBox.Show("SOLIDWORKS 2017");
break;
case "11000":
return "25";
MessageBox.Show("SOLIDWORKS 2018");
break;
case "12000":
return "26";
MessageBox.Show("SOLIDWORKS 2019");
break;
case "13000":
return "27";
MessageBox.Show("SOLIDWORKS 2020");
break;
case "14000":
return "28";
MessageBox.Show("SOLIDWORKS 2021");
break;
case "15000":
return "29";
MessageBox.Show("SOLIDWORKS 2022");
break;
default:
return null;
}
}
使用
//返回一串自编的版本代号,支持多版本以将","隔开进行区分
//SW本身高版本支持低版本文件
SwAddin.VersionIdentify(FilePath[i]);
二、保存或打包文件
1.保存方法体
暂知可保存成STEP或零件,未深入理解
/// <summary>
/// 保存当前工作区
/// </summary>
public static void AddSaveAs()
{
ModelDoc2 Part = default(ModelDoc2);
int File = 0;
Part = (ModelDoc2)iSwApp.ActiveDoc;
File = Part.SaveAs3(@"D:\s-easy.cn\SW", 0, 0);
}
2.打包方法体
*
/// <summary>
/// 打包模型
/// </summary>
/// <param name="swDoc">目标文档</param>
/// <param name="sPackPath">打包文件的存放路径</param>
/// <param name="sPrefix">增加前缀</param>
/// <param name="sSuffix">增加后缀</param>
/// <returns>打包总装名称</returns>
public static string[] PackAndGo(string sPackPath, string sPrefix, string sSuffix)
{
try
{
string[] path = new string[] { "" };
string sPackFile = "";
ModelDoc2 swDoc = (ModelDoc2)iSwApp.ActiveDoc;
if (swDoc.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)
{
MessageBox.Show("只能打包装配体文档");
return path;
}
if (!Directory.Exists(sPackPath)) Directory.CreateDirectory(sPackPath);//创新文件夹
swDoc.ViewZoomtofit2();//全屏显示
bool boolstatus = swDoc.EditRebuild3();
PackAndGo swPackAndGo = (PackAndGo)swDoc.Extension.GetPackAndGo();//获取打包模型文档
swPackAndGo.IncludeDrawings = true;//同时打包工程图
object PathName, DocStatus;
bool status = swPackAndGo.GetDocumentSaveToNames(out PathName, out DocStatus);
string[] sPathName = (string[])PathName;
for (int i = 0; i < sPathName.Length; i++)
{
string sPath = Path.GetDirectoryName(sPathName[i]);
if (!Directory.Exists(sPath))
{
return path;
}
string sName = Path.GetFileName(sPathName[i]);
if (!System.IO.File.Exists(sPathName[i]))
{
return path;
}
string[] FInfo = Directory.GetFiles(sPath, sName, SearchOption.TopDirectoryOnly);
sPathName[i] = sPackPath + "\\" + Path.GetFileName(FInfo[0]);
}
BStrWrapper[] dispwrap = new BStrWrapper[sPathName.Length];
for (int i = 0; i < sPathName.Length; i++)
{
dispwrap[i] = new BStrWrapper(sPathName[i]);
}
status = swPackAndGo.SetDocumentSaveToNames(dispwrap);
if (sPrefix != "") swPackAndGo.AddPrefix = sPrefix;//添加前缀
if (sSuffix != "") swPackAndGo.AddSuffix = sSuffix;//添加后缀
int[] statuses = (int[])swDoc.Extension.SavePackAndGo(swPackAndGo);
string sAssmName = Path.GetFileNameWithoutExtension(swDoc.GetPathName());
sPackFile = sPackPath + "\\" + sPrefix + sAssmName + sSuffix + ".sldasm";//返回打包后的总装配名称
path = new string[dispwrap.Length];//创建一个数组存储文件目录
for (int i = 0; i < dispwrap.Length; i++)
{
path[i] = dispwrap[i].WrappedObject;//文件目录
}
return path;
}
catch (Exception ex)
{
}
return null;
}
使用
string[] FilePath = SwAddin.PackAndGo(@"D:\s-easy.cn\SW\Packaging", null, null);
三、获取当前工作区"盒子"X,Y,Z
模版SwAddin.cs中编写(未精减)
public static double GetMax(double Val1, double Val2, double Val3)
{
double functionReturnValue = 0;
// 找到3个值的最大值
// Finds maximum of 3 values
functionReturnValue = Val1;
if (Val2 > functionReturnValue)
{
functionReturnValue = Val2;
}
if (Val3 > functionReturnValue)
{
functionReturnValue = Val3;
}
return functionReturnValue;
}
public static double GetMin(double Val1, double Val2, double Val3)
{
double functionReturnValue = 0;
// 找到3个值的最小值
// Finds minimum of 3 values
functionReturnValue = Val1;
if (Val2 < functionReturnValue)
{
functionReturnValue = Val2;
}
if (Val3 < functionReturnValue)
{
functionReturnValue = Val3;
}
return functionReturnValue;
}
public static void Main(string ModelFile)
{
const double MaxDouble = 0;
const double MinDouble = 0;
ModelDoc2 swModel = default(ModelDoc2);
AssemblyDoc swAssy = default(AssemblyDoc);
Configuration swConfig = default(Configuration);
ConfigurationManager swConfigurationMgr = default(ConfigurationManager);
Component2 swRootComp = default(Component2);
object[] vChild = null;
Component2 swChildComp = default(Component2);
object Box = null;
double[] BoxArray = new double[6];
double X_max = 0;
double X_min = 0;
double Y_max = 0;
double Y_min = 0;
double Z_max = 0;
double Z_min = 0;
SketchPoint[] swSketchPt = new SketchPoint[9];
SketchSegment[] swSketchSeg = new SketchSegment[13];
int i = 0;
if (iSwApp.GetDocumentCount() == 0)
{
MessageBox.Show("没有SolidWorks文件!", "提示信息");
return;
}
swModel = (ModelDoc2)iSwApp.ActiveDoc;
// 判断该活动文档是否为零部件
if (swModel.GetType() != (int)swDocumentTypes_e.swDocASSEMBLY)
{
MessageBox.Show("活动文档不是装配体,请选择装配体!", "提示信息");
return;
}
swAssy = (AssemblyDoc)swModel;
swConfigurationMgr = (ConfigurationManager)swModel.ConfigurationManager;
swConfig = (Configuration)swConfigurationMgr.ActiveConfiguration;
swRootComp = (Component2)swConfig.GetRootComponent3(true);
// 初始化值
// Initialize values
X_max = MinDouble;
X_min = MaxDouble;
Y_max = MinDouble;
Y_min = MaxDouble;
Z_max = MinDouble;
Z_min = MaxDouble;
vChild = (object[])swRootComp.GetChildren();
for (i = 0; i <= vChild.GetUpperBound(0); i++)
{
swChildComp = (Component2)vChild[i];
if (swChildComp.Visible == (int)swComponentVisibilityState_e.swComponentVisible)
{
Box = (object)swChildComp.GetBox(false, false);
if (Box + "" != "System.Double[]")
{
}
else
{
BoxArray = (double[])Box;
X_max = GetMax(BoxArray[0], BoxArray[3], X_max);
X_min = GetMin(BoxArray[0], BoxArray[3], X_min);
Y_max = GetMax(BoxArray[1], BoxArray[4], Y_max);
Y_min = GetMin(BoxArray[1], BoxArray[4], Y_min);
Z_max = GetMax(BoxArray[2], BoxArray[5], Z_max);
Z_min = GetMin(BoxArray[2], BoxArray[5], Z_min);
}
}
}
if (true)
{
}
if (X_max != 0)
{
X_max += 0.095;
Y_max += 0.095;
Z_max += 0.095;
}
//启动第四套方法
InsertComponent(ModelFile, X_max, Y_max, Z_max);
}
四、打开SW文件到当前指定的X,Y,Z上
模版SwAddin.cs中编写(未精减)
static AssemblyDoc assemb;
static string[] compNames = new string[1];
static double[] compXforms = new double[16];
static string[] compCoordSysNames = new string[1];
static object vcompNames;
static object vcompXforms;
static object vcompCoordSysNames;
static object vcomponents;
public static void InsertComponent(string ModelFile, double X, double Y, double Z)
{
assemb = (AssemblyDoc)iSwApp.ActiveDoc;
if (((assemb != null)))
{
//ModelFileName[0];
compNames[0] = ModelFile;
// 定义变换矩阵.请参阅IMathTransform API文档.
// Define the transformation matrix. See the IMathTransform API documentation.
// 在变换中添加一个旋转对角单位矩阵(零旋转)
// Add a rotational diagonal unit matrix (zero rotation) to the transform
// 旋转的X轴分量
// x-axis components of rotation
compXforms[0] = 1.0;
compXforms[1] = 0.0;
compXforms[2] = 0.0;
// 旋转的Y轴分量
// y-axis components of rotation
compXforms[3] = 0.0;
compXforms[4] = 1.0;
compXforms[5] = 0.0;
// 旋转的Z轴分量
// z-axis components of rotation
compXforms[6] = 0.0;
compXforms[7] = 0.0;
compXforms[8] = 1.0;
// 向转换添加一个平移向量(零平移)
// Add a translation vector to the transform (zero translation)
compXforms[9] = X;
compXforms[10] = Y;
compXforms[11] = Z;
// 在变换中添加一个比例因子
// Add a scaling factor to the transform
compXforms[12] = 0.0;
// 转换矩阵中的最后三个元素是未使用的
// The last three elements in the transformation matrix are unused
// 为组件注册坐标系统名
// Register the coordinate system name for the component
compCoordSysNames[0] = "Coordinate System1";
// 将组件添加到程序集中.
// Add the components to the assembly.
vcompNames = compNames;
vcompXforms = compXforms;
//vcompXforms = Nothing
//也实现了构件的零旋转和平移
//also achieves zero rotation and translation of the component
vcompCoordSysNames = compCoordSysNames;
vcomponents = assemb.AddComponents3((vcompNames), (vcompXforms), (vcompCoordSysNames));
}
}
// SldWorks swApp变量是预先为您分配的.
// The SldWorks swApp variable is pre-assigned for you.
public static SldWorks swApp;
五、工具栏的设置
模版SwAddin.cs中自带,找不同点进行修改(未精减)
public void AddCommandMgr()
{
ICommandGroup cmdGroup;
if (iBmp == null)
iBmp = new BitmapHandler();
Assembly thisAssembly;
int cmdIndex0, cmdIndex1, cmdIndex2;
//名称和提示文件
string Title = "工业助理", ToolTip = "工具提醒";
int[] docTypes = new int[]{(int)swDocumentTypes_e.swDocASSEMBLY,
(int)swDocumentTypes_e.swDocDRAWING,
(int)swDocumentTypes_e.swDocPART};
thisAssembly = System.Reflection.Assembly.GetAssembly(this.GetType());
int cmdGroupErr = 0;
bool ignorePrevious = false;
object registryIDs;
//获取存储在注册表中的ID信息
//get the ID information stored in the registry
bool getDataResult = iCmdMgr.GetGroupDataFromRegistry(mainCmdGroupID, out registryIDs);
int[] knownIDs = new int[3] { mainItemID1, mainItemID2, mainItemID3 };
if (getDataResult)
{
//如果id不匹配,重置命令组
if (!CompareIDs((int[])registryIDs, knownIDs))//if the IDs don't match, reset the commandGroup
{
ignorePrevious = true;
}
}
//图标,尽可能不动,可能丢失图标
cmdGroup = iCmdMgr.CreateCommandGroup2(mainCmdGroupID, Title, ToolTip, "", -1, ignorePrevious, ref cmdGroupErr);
cmdGroup.LargeIconList = iBmp.CreateFileFromResourceBitmap("Addin2014.ToolbarLarge.bmp", thisAssembly);
cmdGroup.SmallIconList = iBmp.CreateFileFromResourceBitmap("Addin2014.ToolbarSmall.bmp", thisAssembly);
cmdGroup.LargeMainIcon = iBmp.CreateFileFromResourceBitmap("Addin2014.MainIconLarge.bmp", thisAssembly);
cmdGroup.SmallMainIcon = iBmp.CreateFileFromResourceBitmap("Addin2014.MainIconSmall.bmp", thisAssembly);
//增加按钮(工具栏的"触发器")
int menuToolbarOption = (int)(swCommandItemType_e.swMenuItem | swCommandItemType_e.swToolbarItem);
cmdIndex1 = cmdGroup.AddCommandItem2("模型库", -1, "模型库", "模型库", 1, "ShowPMP", "", mainItemID2, menuToolbarOption);
cmdIndex0 = cmdGroup.AddCommandItem2("用户登录", -1, "用户登录", "用户登录", 12, "Login", "", mainItemID1, menuToolbarOption);
cmdIndex2 = cmdGroup.AddCommandItem2("上传数模", -1, "上传数模", "上传数模", 0, "Upload", "", mainItemID3, menuToolbarOption);
cmdGroup.HasToolbar = true;
cmdGroup.HasMenu = true;
cmdGroup.Activate();
bool bResult;
foreach (int type in docTypes)
{
CommandTab cmdTab;
cmdTab = iCmdMgr.GetCommandTab(type, Title);
//如果选项卡存在,但是我们忽略了注册表信息(或更改了命令组ID),那么重新创建选项卡.否则id将不匹配,标签将是空白的
if (cmdTab != null & !getDataResult | ignorePrevious)//if tab exists, but we have ignored the registry info (or changed command group ID), re-create the tab. Otherwise the ids won't matchup and the tab will be blank
{
bool res = iCmdMgr.RemoveCommandTab(cmdTab);
cmdTab = null;
}
//如果cmdTab为空,必须首先加载(可能在重置之后),将命令添加到选项卡
//if cmdTab is null, must be first load (possibly after reset), add the commands to the tabs
if (cmdTab == null)
{
cmdTab = iCmdMgr.AddCommandTab(type, Title);
CommandTabBox cmdBox = cmdTab.AddCommandTabBox();
int[] cmdIDs = new int[3];
int[] TextType = new int[3];
//按钮样式
cmdIDs[0] = cmdGroup.get_CommandID(cmdIndex1);
TextType[0] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow;
cmdIDs[1] = cmdGroup.get_CommandID(cmdIndex0);
TextType[1] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow;
cmdIDs[2] = cmdGroup.get_CommandID(cmdIndex2);
TextType[2] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow;
bResult = cmdBox.AddCommands(cmdIDs, TextType);
}
}
thisAssembly = null;
}
六、将用户控件切入成左侧属性页
模版SwAddin.cs中编写,方法名和工具栏第六个参数相同,存在消失情况(PropertyManager)
public void ShowPMP()
{
if (SwAddin.Main1(1) != 0)
{
MessageBox.Show("要关闭页面");
}
else
{
string user_token = PublicStaticClass.User_token;
if (user_token == null)
{
Login();
}
else
{
//UserPMPage
if (ppage != null)
{
ppage.Show();
}
else
{
ppage = new UserPMPage(this);
ppage.Show();
}
}
}
}
你的用户控件中编写(未精减)
using SolidWorks.Interop.sldworks;
using System;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
namespace Addin2014.Page
{
public partial class IAModelLibrary : UserControl
{
public UserPMPage PmPage;
public IAModelLibrary(UserPMPage PMPage)
{
InitializeComponent();
PmPage = PMPage;
BackColor = Color.FromArgb(247, 247, 247);
}
模版UserPMPage.cs中编写
protected void AddControls()
{
short controlType = -1;
short align = -1;
int options = -1;
//Add the groups
options = (int)swAddGroupBoxOptions_e.swGroupBoxOptions_Expanded |
(int)swAddGroupBoxOptions_e.swGroupBoxOptions_Visible;
group1 = (IPropertyManagerPageGroup)swPropertyPage.AddGroupBox(group1ID, "模型库", options);
controlType = (int)swPropertyManagerPageControlType_e.swControlType_WindowFromHandle;
align = (int)swPropertyManagerPageControlLeftAlign_e.swControlAlign_LeftEdge;
options = (int)swAddControlOptions_e.swControlOptions_Enabled |
(int)swAddControlOptions_e.swControlOptions_Visible;
//添加用户控件
IAModelLibrary = (PropertyManagerPageWindowFromHandle)group1.AddControl(1, controlType, "标题", align, options, "");
//用户控件最大占用高度
IAModelLibrary.Height = 320;
}
public void Show()
{
IAModelLibrary MyPMPControlPage = new IAModelLibrary(this);
//Temporary Variable = TV
var TV = IAModelLibrary.SetWindowHandlex64(MyPMPControlPage.Handle.ToInt32());
if (swPropertyPage != null)
{
swPropertyPage.Show();
}
}
七、左侧属性页是否打开
判断叫工业助理的打开没
public static int Main1(int i)
{
ModelDoc2 swModel = default(ModelDoc2);
ModelDocExtension swModelDocExt = default(ModelDocExtension);
string pageName = null;
swModel = (ModelDoc2)iSwApp.ActiveDoc;
swModelDocExt = (ModelDocExtension)swModel.Extension;
// 在即时窗口中打印active PropertyManager页面的名称
// Print the name of the active PropertyManager page in the Immediate window
pageName = swModelDocExt.GetActivePropertyManagerPage();
//是否叫工业助理
if (pageName == "uiDveApiPage2_c")
{
return 1;
}
else if (pageName == "")
{
return 0;
}
else
{
return 2;
}
}