using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.IO;
namespace YourNamespace
{
class YourClass
{
// 定义常量:输出文件路径和单位转换因子
const string OUT_FILE_PATH = @"D:\locations.csv";
const double CONV_FACTOR = 1000; // 米转换为毫米
static SldWorks swApp;
static void Main(string[] args)
{
// 初始化SolidWorks应用程序对象
swApp = Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application")) as SldWorks;
// 获取当前激活的装配文档
ModelDoc2 swAssy = swApp.ActiveDoc as ModelDoc2;
if (swAssy != null)
{
// 获取用户选择的第一个组件
Component2 swSeedComp = GetSelectedComponent(swAssy);
if (swSeedComp != null)
{
// 获取装配中所有组件的位置信息
string table = GetComponentsPositions(swAssy, swSeedComp, CONV_FACTOR);
// 将位置信息写入文本文件
WriteTextFile(OUT_FILE_PATH, table);
}
else
{
Console.WriteLine("未选择组件");
}
}
else
{
Console.WriteLine("请打开装配");
}
}
// 获取用户选择的组件
static Component2 GetSelectedComponent(ModelDoc2 assy)
{
Component2 swSeedComp = null;
// 获取用户选择的第一个组件
object[] selectedObjs = assy.SelectionManager.GetSelectedObjectsComponent4(1, -1);
if (selectedObjs.Length > 0)
{
swSeedComp = selectedObjs[0] as Component2;
}
return swSeedComp;
}
// 获取所有组件的位置信息
static string GetComponentsPositions(ModelDoc2 assy, Component2 seedComp, double convFactor)
{
// 初始化位置信息表格的表头
string table = "Path,Configuration,Name,X,Y,Z";
// 获取装配中的所有组件
Component2[] vComps = assy.GetComponents(false) as Component2[];
foreach (Component2 swComp in vComps)
{
// 检查组件是否被抑制
if (swComp.GetSuppression() != (int)swComponentSuppressionState_e.swComponentSuppressed)
{
bool includeComp = (seedComp == null) ||
(string.Compare(seedComp.GetPathName(), swComp.GetPathName(), StringComparison.OrdinalIgnoreCase) == 0 &&
string.Compare(seedComp.ReferencedConfiguration, swComp.ReferencedConfiguration, StringComparison.OrdinalIgnoreCase) == 0);
if (includeComp)
{
// 获取组件的原点坐标并添加到table中
double[] vOrigin = GetOrigin(swComp);
table += Environment.NewLine +
swComp.GetPathName() + "," +
swComp.ReferencedConfiguration + "," +
swComp.Name2 + "," +
(vOrigin[0] * convFactor).ToString() + "," +
(vOrigin[1] * convFactor).ToString() + "," +
(vOrigin[2] * convFactor).ToString();
}
}
}
return table;
}
// 获取组件的原点坐标
static double[] GetOrigin(Component2 comp)
{
// 获取组件的变换矩阵
MathTransform swXForm = comp.Transform2;
// 获取数学工具
MathUtility swMathUtils = swApp.GetMathUtility() as MathUtility;
// 创建表示原点的数学点
double[] dPt = new double[3] { 0, 0, 0 };
MathPoint swMathPt = swMathUtils.CreatePoint(dPt);
// 使用组件的变换将原点坐标转换到装配坐标系
swMathPt = swMathPt.MultiplyTransform(swXForm) as MathPoint;
// 返回原点坐标
return (double[])swMathPt.ArrayData;
}
// 将文本内容写入文件
static void WriteTextFile(string filePath, string content)
{
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write(content);
}
}
catch (Exception ex)
{
Console.WriteLine("写入文件时出错:" + ex.Message);
}
}
}
}