C# SolidWorks二次开发:模块化装配程序
C#初学者作品展示,自动完成装配过程
使用说明书
待编辑
添加配合的原理
待编辑
源代码
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SolidWorksSDK
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//防止重复打开
bool ProgramLock;
new System.Threading.Mutex(true, "主窗体启动", out ProgramLock);
if (!ProgramLock) MessageBox.Show("本程序已运行!\r如出现错误请重启电脑", "程序已运行", MessageBoxButtons.OK, MessageBoxIcon.Information);
else Application.Run(new MainForm());
}
}
}
MainForm.cs
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
namespace SolidWorksSDK
{
public partial class MainForm : Form
{
#region 全局变量
private XML_BaseDate BaseDate;
#endregion
#region 基础方法
private class XML_BaseDate : XML
{
public XML_BaseDate(string FullPath) : base(FullPath) {
}
public void Initialize()//初始化数据
{
Doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
Doc.Add(new XElement("BaseDate", new XAttribute("LastConfiguration_Assembly", "null")));
Doc.Save(DocFullPath);
}
}
public MainForm()
{
Background.MainFormObject = this;
InitializeComponent();
}//初始化
private void Form_Initialize(object sender, EventArgs e)
{
//初始化基础数据
BaseDate = new XML_BaseDate(Background.MyDocuments + "\\MainInt.sdk0");
Directory.CreateDirectory(Background.MyDocuments);
if (!File.Exists(Background.MyDocuments + "\\MainInt.skd0"))
{
BaseDate.Initialize();//如果Basedate文件不存在则初始化基础配置文件
}
else
{
BaseDate.Load();//存在则读取配置,根据配置初始化界面
}
TraverseConfigurationDoc(true);
}
private void Form_Closing(object sender, FormClosingEventArgs e)
{
BaseDate.Save(true);
}
#endregion
private void Test_Click(object sender, EventArgs e)
{
#region 启动并连接SolidWorks
SldWorks.SldWorks SwApp;
if (System.Type.GetTypeFromProgID("Sldworks.application") != null)
{
SwApp = (SldWorks.SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID("Sldworks.application"));
if (SwApp != null)
{
SwApp.Visible = true;
}
else
{
MessageBox.Show("SolidWorks启动失败", "未知错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("SolidWorks启动失败", "未知错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
public void TraverseConfigurationDoc(bool AsLast)
{
DirectoryInfo WorkingDir = new DirectoryInfo(Background.MyDocuments);
FileInfo[] FileInfo_Assembly = WorkingDir.GetFiles("*.sdk1", SearchOption.TopDirectoryOnly);
if (FileInfo_Assembly.Count() == 0)
{
return;
}
comboBox_Assembly.Items.Clear();
comboBox_Assembly.Items.AddRange(FileInfo_Assembly);
string LastConfiguration_Assembly = BaseDate.Doc.Element("BaseDate").Attribute("LastConfiguration_Assembly").Value;//读取配置
comboBox_Assembly.Text = comboBox_Assembly.Items[0].ToString();
if (AsLast) //显示为文件名
{
foreach (FileInfo flag_0 in FileInfo_Assembly)//显示为上一次打开的文件名
{
if (flag_0.ToString() == LastConfiguration_Assembly)
{
comboBox_Assembly.Text = LastConfiguration_Assembly;
break;
}
}
}
}
private void AssemblyProgram_button_Click(object Message, EventArgs e)
{
if (File.Exists(Background.MyDocuments + "\\" + comboBox_Assembly.Text))
{
if (Background.AsmFormObject == null)
{
Form_AssemblyProgram Form_Assembly = new Form_AssemblyProgram(Background.MyDocuments + "\\" + comboBox_Assembly.Text);
Background.AsmFormObject = Form_Assembly;
BaseDate.Doc.Element("BaseDate").Attribute("LastConfiguration_Assembly").Value = comboBox_Assembly.Text;
}
else
{
MessageBox.Show("本程序已运行!\r如出现错误请重启程序", "程序已运行", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
if (MessageBox.Show("配置文件不存在,是否初始化?", "错误", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
if (Background.AsmFormObject == null)
{
Form_AssemblyProgram Form_Assembly = new Form_AssemblyProgram("初始化");
Background.AsmFormObject = Form_Assembly;
TraverseConfigurationDoc(false);
}
else
{
MessageBox.Show("本程序已运行!\r如出现错误请重启程序", "程序已运行", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
TraverseConfigurationDoc(false);
}
}
}//实例化装配程序窗体
}
}
Form_AssemblyProgram.cs
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Linq;
namespace SolidWorksSDK
{
public partial class Form_AssemblyProgram : Form_Dynamic
{
#region 全局变量
public XML_Configuration FirstConf;
public XML_Configuration CurrentConf;
public bool[] CompOptionLock;
public bool AsmOptionLock;
public Button[] Button_0;
private readonly ToolTip ToolTip_0;
private Thread AsmProgramThread = null;
private Background.AsmProgram AsmProgram;
private TextBox TextBox_0;
#endregion
#region 基础方法
#region Class
public class XML_Configuration : XML
{
#region 全局变量
public XElement[] CompElements {
get; private set; }
public XElement[] InsertElements {
get; private set; }
public XElement[] MateElements {
get; private set; }
public string[] CompClassName {
get; private set; }
#endregion
public XML_Configuration(string FullPath) : base(FullPath)
{
if (FullPath == "TempPath")
{
Directory.CreateDirectory(Environment.GetEnvironmentVariable("TMP") + "\\SugarSolidWorksSDK");
DocFullPath = System.Environment.GetEnvironmentVariable("TMP") + "\\SugarSolidWorksSDK\\Temp.sdk1";
}
}
public void Initialize()
{
Element = new XElement[4];
Doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
Element[0] = new XElement("AssemblyProgram");
#region 生成BaseDate(基础数据)空文档
Element[0].Add(new XElement("BaseDate",
new XAttribute("SavePath", "D:\\实验室\\测试装配体1.sldasm"),
new XAttribute("ASMDOT", "C:\\Users\\86156\\Desktop\\gb_assembly.asmdot"),
new XAttribute("AssemblyOrder", "0")
));
#endregion
#region 生成CompInfo(部件信息)空文档
Element[1] = new XElement("CompInfo");
for (int flag_0 = 0; flag_0 <= 5; flag_0++)
{
Element[2] = new XElement("Component_" + flag_0.ToString(),
new XAttribute("ClassName", "测试部件_" + flag_0.ToString()),
new XAttribute("CompPath", "D:\\实验室\\测试装配体.sldasm"),
new XAttribute("OpenMode", "ReadOnly"));
for (int flag_1 = 0; flag_1 <= 3; flag_1++)
{
Element[3] = new XElement("Reference_" + flag_1.ToString(),
new XAttribute("Type", "Plane"),
new XAttribute("Name", "基准特征名称" + flag_1.ToString()));
Element[2].Add(Element[3]);
}//生成基准信息
for (int flag_2 = 0; flag_2 <= 5; flag_2++)
{
Element[3] = new XElement("Parameter_" + flag_2.ToString(),
new XAttribute("Name", "自定义属性名称_" + flag_2.ToString()),
new XAttribute("Value", "0"));
Element[2].Add(Element[3]);
}//生成装配参数信息
Element[1].Add(Element[2]);
}//生成部件信息
Element[0].Add(Element[1]);
#endregion
#region 生成MateInfo(配合信息)空文档
Element[1] = new XElement("MateInfo");
for (int flag_0 = 0; flag_0 <= 7; flag_0++)
{
Element[2] = new XElement("InsertComp_" + flag_0.ToString(),
new XAttribute("Object", "测试部件_1"),
new XAttribute("Localtion", "1.5#2.6#3.7"),
new XAttribute("Float", "true"),
new XAttribute("Configuration", "默认"));
Element[1].Add(Element[2]);
}//生成部件插入信息
for (int flag_0 = 0; flag_0 <= 30; flag_0++)
{
Element[2] = new XElement("Mate_" + flag_0.ToString(),
new XAttribute("MateName", "测试配合_" + flag_0.ToString()),
new XAttribute("Align", "false"),
new XAttribute("Flip", "false"),
new XAttribute("MateType", "距离"),
new XAttribute("MateValue", "#摆架行程@2=650#1000#安装面-合模中心面@1"));
for (int flag_1 = 0; flag_1 <= 4; flag_1++)
{
Element[3] = new XElement("MateObject_" + flag_1.ToString(),
new XAttribute("SelectionMode", "ByName"),
new XAttribute("SelectionInfo", "合模中心面@0"));
Element[2].Add(Element[3]);
}
Element[1].Add(Element[2]);
}
Element[0].Add(Element[1]);
#endregion
Doc.Add(Element[0]);
}
public override void Load()
{
Doc = XDocument.Load(DocFullPath);
#region 把部件对象写入数组
CompElements = (from flag_0 in Doc.Element("AssemblyProgram").Element("CompInfo").Elements() where flag_0.Name.ToString().Contains("Component_") select flag_0).ToArray();
InsertElements = (from flag_0 in Doc.Element("AssemblyProgram").Element("MateInfo").Elements() where flag_0.Name.ToString().Contains("InsertComp_") select flag_0).ToArray();
MateElements = (from flag_0 in Doc.Element("AssemblyProgram").Element("MateInfo").Elements() where flag_0.Name.ToString().Contains("Mate_") select flag_0).ToArray();
CompClassName = new string[CompElements.Length];
for (int flag_0 = 0; flag_0 < CompElements.Length; flag_0++) CompClassName[flag_0] = CompElements[flag_0].Attribute("ClassName").Value;
#endregion
}
}
private class TempForm_CompOption : Form_Dynamic
{
#region 全局变量
private readonly Button Sender;
private readonly XElement CompElement;
private TextBox TextBox_0;
private ComboBox ComboBox_0;
public XElement[] ReferenceElements {
get; private set; }
public XElement[] ParameterElements {
get; private set; }
public int ReferenceCount {
get; private set; }
public int ParameterCount {
get; private set; }
#endregion
public TempForm_CompOption(object sender) : base(sender)
{
Sender = (Button)sender;
int.TryParse(Sender.Name.Split('_')[2], out int CompNumber);
CompElement = Background.AsmFormObject.CurrentConf.Doc.Element("AssemblyProgram").Element("CompInfo").Element("Component_" + CompNumber.ToString());//必须链接到文档,防止写入失败;
#region 设置对象
ReferenceElements = (from flag_0 in CompElement.Elements() where flag_0.Name.ToString().Contains("Reference_") select flag_0).ToArray();
ParameterElements = (from flag_0 in CompElement.Elements() where flag_0.Name.ToString().Contains("Parameter_") select flag_0).ToArray();
ReferenceCount = ReferenceElements.Length;
ParameterCount = ParameterElements.Length;
#endregion
#region 窗体属性
AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
MaximumSize = new System.Drawing.Size(500, 500);
MinimumSize = new System.Drawing.Size(200, 200);
AutoScroll = true;
Name = CompElement.Attribute("ClassName").Value;
Text = CompElement.Attribute("ClassName").Value + " : 部件属性";
ResumeLayout(false);
PerformLayout();
#endregion
CreateButtons();
Visible = true;
}//初始化
public override void From_Closing(object sender, FormClosingEventArgs e)
{
WriteXML();//关闭前把数据写入CurrentXML
int.TryParse(Sender.Name.Split('_')[2], out int flag_0);
Background.AsmFormObject.CompOptionLock[flag_0] = false;
Background.AsmFormObject.Visible = true;
Dispose();
}
private void CreateButtons()
{
string[] ReferenceItem = new string[] {
"Plane", "Axis", "Surface" };
int X1 = 10; int W1 = 100; int X2 = X1 + W1 + 10; int W2 = 100; int Y = 10; int H = 20;
TextBoxCreated = new TextBox[ReferenceCount + 2 * ParameterCount]; //实例化数组
ComboBoxCreated = new ComboBox[ReferenceCount];
#region 实例化按钮
#region 一次性控件
TextBox_0 = new TextBox
{
Name = CompElement.Attribute("ClassName").Value,
Text = CompElement.Attribute("ClassName").Value,
Location = new System.Drawing.Point(X1, Y),
Size = new System.Drawing.Size(W1, H),
AutoSize = false
};
ComboBox_0 = new ComboBox
{
Name = CompElement.Attribute("ClassName").Value,
Location = new System.Drawing.Point(X2, Y),
Size = new System.Drawing.Size(W2, H),
DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList, // 设置为不可编辑Combox
FormattingEnabled = true,
ImeMode = System.Windows.Forms.ImeMode.NoControl,
Sorted = false
};
string[] OpenMode = new string[] {
"ReadOnly", "Silent", "ViewOnly", "LoadLightweight" };
ComboBox_0.Items.AddRange(OpenMode);
ComboBox_0.Text = (string)ComboBox_0.Items[0];
foreach (string flag_1 in OpenMode)
{
if (flag_1 == CompElement.Attribute("OpenMode").Value)
{
ComboBox_0.Text = flag_1;
}
}
Controls.Add(TextBox_0);
Controls.Add(ComboBox_0);
Y += H + 5;
#endregion
for (int flag_0 = 0; flag_0 < ReferenceCount + ParameterCount; flag_0++)
{
if (flag_0 < ReferenceCount)
{
#region ComboBox
ComboBoxCreated[flag_0] = new ComboBox
{
Name = "Reference_" + flag_0.ToString(),
Location = new System.Drawing.Point(X1, Y),
Size = new System.Drawing.Size(W1, H),
DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList, // 设置为不可编辑Combox
FormattingEnabled = true,
ImeMode = System.Windows.Forms.ImeMode.NoControl,
Sorted = false
};
ComboBoxCreated[flag_0].Items.AddRange(ReferenceItem);
ComboBoxCreated[flag_0].Text = (string)ComboBoxCreated[flag_0].Items[0];
foreach (string flag_1 in ReferenceItem)
{
if (flag_1 == CompElement.Element("Reference_" + flag_0.ToString()).Attribute("Type").Value)
{
ComboBoxCreated[flag_0].Text = flag_1;
}
}
#endregion
TextBoxCreated[flag_0] = new TextBox
{
Name = "Reference_Name_" + flag_0.ToString(),
Text = CompElement.Element("Reference_" + flag_0.ToString()).Attribute("Name").Value,
Location = new System.Drawing.Point(X2, Y),
Size = new System.Drawing.Size(W2, H),
AutoSize = false
};
TextBoxCreated[flag_0].Leave += new System.EventHandler(TextCheck);
Controls.Add(ComboBoxCreated[flag_0]);
Controls.Add(TextBoxCreated[flag_0]);
}
else
{
int flag_2 = (flag_0 - ReferenceCount);
TextBoxCreated[flag_0] = new TextBox
{
Name = "Parameter_Name_" + flag_2.ToString(),
Text = CompElement.Element("Parameter_" + flag_2.ToString()).Attribute("Name").Value,
Location = new System.Drawing.Point(X1, Y),
Size = new System.Drawing.Size(W1, H),
AutoSize = false
};
TextBoxCreated[flag_0].Leave += new System.EventHandler(TextCheck);
TextBoxCreated[flag_0 + ParameterCount] = new TextBox
{
Name = "Parameter_Value_" + flag_2.ToString(),
Text = CompElement.Element("Parameter_" + flag_2.ToString()).Attribute("Value").Value,
Location = new System.Drawing.Point(X2, Y),
Size = new System.Drawing.Size(W2, H),
AutoSize = false
};
Controls.Add(TextBoxCreated[flag_0]);
Controls.Add(TextBoxCreated[flag_0 + ParameterCount]);
}
Y += H + 5;
}//循环生成控件
Width = X2 + W2 + 25;
Height = Y + H + 20;
#endregion
}
private void WriteXML()