# AutoCAD.EntityTools
**Repository Path**: gwhsss/auto-cad.-entity-tools
## Basic Information
- **Project Name**: AutoCAD.EntityTools
- **Description**: cad封装的帮助方法...
- **Primary Language**: C#
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 1
- **Forks**: 0
- **Created**: 2025-01-01
- **Last Updated**: 2025-09-18
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
CAD二次开发对实体类做出的扩展...
## 安装教程
dotnet add package AutoCAD.EntityTool --version 1.0.5
[nuget](https://www.nuget.org/packages/AutoCAD.EntityTool/)

## 项目结构
* AutoCAD.EntityTools CAD二次开发工具
* AutoCAD.EntityTool.Tests 测试工具
* AutoCAD.EntityTools.ConsoleTests 控制台测试
## 类结构
* EntityTools Entity类扩展
* PointTools Point类扩展
* LayerTools Layer类扩展
* EditorTools Editor类扩展
* BlockTools Block类扩展
* ArcTools Arc类扩展
* BlockTools Block类扩展
* CadFileOperation File扩展
* CurveTools Curve类扩展
* DimensionTools Dimension扩展
* DoubleTools Double类扩展
* ExceptionTools Exception类扩展
* LineTools Line类扩展
* PolylineTools Polyline类扩展
* ShowMessageTools ShowMessage扩展
* StringTools String类扩展
* TextTools Text类扩展
* UnitTools Unit扩展
* VectorTools Vector扩展
* Jig CircleJig 、 LineJig 、 RectangleJig
* ConfigPath 配置类
* DwgToDxfConverter 转换器
* RibbonBuilderBase Ribbon封装类
* PaletteHelper 停靠面板
* RegistryManage 注册表封装类
* GlobalUsings 全局引用
### 调用方式
``` CSharp
using AutoCAD.EntityTools;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
[assembly:CommandClass(typeof(AutoCAD.Entitytools.Test.Demo))]
namespace AutoCAD.Entitytools.Test
{
public class Demo
{
[CommandMethod(nameof(Run1))]
public void Run1()
{
try
{
var doc = Application.DocumentManager.MdiActiveDocument;
using (doc.LockDocument())
{
var line = new Line(Point3d.Origin, new Point3d(10, 10, 0));
doc.Database.AddEntityToModelSpace(line);
}
"完成了".CadAlert();
}
catch (System.Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
}
}
```

### 封装方法
##### Entity类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 实体扩展工具类
///
public static class EntityTools
{
///
/// 通过ObjectId数组获取对应的实体数组
///
/// AutoCAD数据库实例
/// 要查询的ObjectId数组
/// 与ObjectId数组对应的实体数组
public static Entity[] ToObjectIdGetEntity(this Database db, params ObjectId[] objIds)
///
/// 通过ObjectId得到实体
///
/// 图形数据库
/// 要查询的ObjectId
/// 实体对象
public static Entity ToObjectIdGetEntity(this Database db, ObjectId objId)
///
/// 移动实体(优化版)
///
/// 实体的ObjectId
/// 移动源点
/// 移动的目标点
/// 是否移动成功
public static bool Move(this ObjectId id, Point3d sourcePt, Point3d targetPt)
///
/// 创建直线并添加到模型空间
///
/// 图形数据库
/// 起点
/// 终点
/// 颜色索引
/// 直线ObjectId
public static ObjectId AddLineToModelSpace(this Database db, Point3d startPoint, Point3d endPoint, short colorIndex = 1)
///
/// 移动实体
///
/// 实体类型
/// 实体
/// 移动源点
/// 移动的目标点
public static void Move(this TEntity ent, Point3d sourcePt, Point3d targetPt) where TEntity : Entity
///
/// 复制实体(安全版本)
///
/// 实体的ObjectId
/// 复制的源点
/// 复制的目标点
/// 复制实体的ObjectId
public static ObjectId Copy(this ObjectId id, Point3d sourcePt, Point3d targetPt)
///
/// 旋转实体(安全版本)
///
/// 实体ObjectId
/// 旋转基点
/// 旋转角度(弧度)
/// 是否旋转成功
public static bool Rotate(this ObjectId id, Point3d basePt, double angle)
///
/// 旋转实体(角度制版本)
///
/// 实体ObjectId
/// 旋转基点
/// 旋转角度(度)
/// 是否旋转成功
public static bool RotateDegrees(this ObjectId id, Point3d basePt, double angleInDegrees)
///
/// 显示所有实体
///
/// 文档对象
public static void ShowAllEntities(this Document doc)
///
/// 隐藏除指定实体列表外的所有其他实体
///
/// 要保持可见的实体ObjectId列表
public static void HideOtherEntities(this List objectIdsToKeepVisible)
///
/// 缩放实体(安全版本)
///
/// 实体的ObjectId
/// 缩放基点
/// 缩放比例
/// 是否缩放成功
public static bool Scale(this ObjectId id, Point3d basePt, double scaleFactor)
///
/// 镜像实体(安全版本)
///
/// 实体ObjectId
/// 镜像点1
/// 镜像点2
/// 是否删除源对象
/// 镜像实体的ObjectId
public static ObjectId Mirror(this ObjectId id, Point3d mirrorPt1, Point3d mirrorPt2, bool eraseSourceObject)
///
/// 将指定的实体添加到AutoCAD图形数据库中的块表记录
///
/// 实体类型
/// 要添加到数据库的实体对象
/// 事务对象
/// 目标块表记录
/// 添加到数据库后实体的ObjectId
public static ObjectId AddToDatabase(this TEntity entity, Transaction host, BlockTableRecord btr) where TEntity : Entity
///
/// 将一组实体添加到AutoCAD图形数据库中的模型空间块表记录
///
/// 实体类型
/// 要添加到数据库的实体集合
/// 事务对象
/// 模型空间块表记录
/// 包含所有添加到数据库后实体的ObjectId的列表
public static List AddToDatabase(this ICollection entities, Transaction host, BlockTableRecord model_space) where TEntity : Entity
///
/// 将一组实体添加到AutoCAD图形数据库中的指定块表记录
///
/// 实体类型
/// 事务对象
/// 块表记录对象
/// 要添加到数据库的实体数组
/// 包含所有添加到数据库后实体的ObjectId的列表
public static List AddEntityToDatabase(this Transaction trans, BlockTableRecord btr, params TEntity[] entities) where TEntity : Entity
///
/// 修改实体的颜色
///
/// 实体Id
/// 颜色索引
public static void ModifyEntityColorIndex(this ObjectId entityId, short newColorIndex)
///
/// 将图形对象添加到图形文件中
///
/// 图形数据库
/// 图形对象
/// 图形的ObjectId
public static ObjectId AddEntityToModelSpace(this Database db, Entity entity)
///
/// 删除图像数据库实体
///
/// 当前文档
/// 实体id
/// 是否删除成功
public static bool DeleteEntities(this Document doc, params ObjectId[] entityIds)
///
/// 判断一个实体是否已经添加到图形数据库
///
/// 实体
///
public static bool IsEntityInDatabase(this Entity entity)
///
/// 删除图像数据库实体
///
/// 文档
/// 实体id
///
public static bool DeleteEntity(this Document doc, ObjectId entityId)
///
/// 将图形对象添加到图形文件中
///
/// 图形数据库
/// 图形对象数组
/// 图形的ObjectId数组
public static ObjectId[] AddEntityToModelSpace(this Database db, params Entity[] entity)
///
/// 修改图形颜色(未添加到图形数据库)
///
/// 实体类型
/// 实体
/// 颜色索引
/// 文档对象
public static void ChangeEntityColor(this TEntity entity, short colorIndex, Document doc) where TEntity : Entity
///
/// 修改图形颜色
///
/// 实体类型
/// 实体
/// 颜色索引
/// 文档对象
public static void ChangeEntityColor2(this TEntity entity, short colorIndex, Document doc) where TEntity : Entity
///
/// 设置实体颜色、图层(安全版本)
///
/// 实体类型,必须继承自AutoCAD的Entity类
/// 实体
/// 颜色索引
/// 图层名字
/// 如果图层不存在是否创建
/// 图层颜色索引(可选)
public static void SetColorLayer(this TEntity entity, short colorIndex, string layerName,
bool createIfNotExists = true, short layerColorIndex = 256) where TEntity : Entity
///
/// 选择一个对象
///
/// 编辑器对象
/// 选择过滤器
/// 选择的ObjectId
public static ObjectId SelectOne(this Editor ed, SelectionFilter filter = default)
///
/// 删除图形对象
///
/// 图形对象的ObjectId
public static void EraseEntity(this ObjectId entity)
///
/// 删除图形对象
///
/// 图形对象的ObjectId数组
public static void EraseEntities(params ObjectId[] entIds)
///
/// 通过ObjectId得到实体
///
/// 实体id数组
/// 图形数据库
/// 实体数组
public static Entity[] GetEntity(this ObjectId[] objIds, Database db)
///
/// 通过ObjectId得到实体
///
/// 实体id
/// 图形数据库
/// 实体对象
public static Entity GetEntity(this ObjectId objId, Database db)
///
/// 通过ObjectId获取指定类型的实体
///
/// 实体类型
/// 文档对象
/// 实体ObjectId
/// 打开模式
/// 是否打开已删除对象
/// 指定类型的实体
public static TEntity GetEntity(this Document doc, ObjectId objId, OpenMode openMode = OpenMode.ForRead, bool openErased = false) where TEntity : Entity
///
/// 通过ObjectId获取实体(非泛型版本)
///
/// 文档对象
/// 实体ObjectId
/// 打开模式
/// 是否打开已删除对象
/// 实体对象
public static Entity GetEntity(this Document doc, ObjectId objId, OpenMode openMode = OpenMode.ForRead, bool openErased = false)
///
/// 通过ObjectId得到实体
///
/// 图形数据库
/// 实体ObjectId
/// 实体对象
public static Entity GetEntity(this Database db, ObjectId objId)
///
/// 通过圆心、起点夹角绘制圆弧
///
/// 图形数据库
/// 圆心
/// 起点
/// 夹角(角度值)
/// 圆弧ObjectId
public static ObjectId AddArcToModelSpace(this Database db, Point3d center, Point3d startPoint, double degree)
///
/// 通过三点绘制圆弧(起点、圆弧上一点、终点)
///
/// 图形数据库
/// 圆弧的起始点
/// 圆弧上的点
/// 圆弧的终止点
/// 圆弧的ObjectId
public static ObjectId AddArcToModelSpace(this Database db, Point3d startPoint, Point3d pointOnArc, Point3d endPoint)
///
/// 绘制圆弧
///
/// 图形数据库
/// 圆弧所在圆的圆心点
/// 圆弧的半径
/// 圆弧的起始角度
/// 圆弧的终止角度
/// 圆弧ObjectId
public static ObjectId AddArcToModelSpace(this Database db, Point3d center, double radius, double startDegree, double endDegree)
///
/// 绘制直线
///
/// 图形数据库
/// 起点坐标
/// 直线长度
/// 与x轴正方向的角度
/// 直线ObjectId
public static ObjectId AddLineToModelSpace(this Database db, Point3d startPoint, double length, double degree)
///
/// 删除图形
///
/// 当前文档
/// 实体id列表
/// 是否删除成功
public static bool DeleteEntities(this Document doc, List entityIds)
///
/// 删除图形数据库实体
///
/// 当前文档
/// 实体id数组
/// 是否删除成功
public static bool DeleteEntities(this Document doc, params ObjectId[] entityIds)
///
/// 删除图形数据库实体
///
/// 当前文档
/// 实体id
/// 是否删除成功
public static bool DeleteEntities(this Document doc, ObjectId entityId)
///
/// 将实体集合添加到模型空间
///
/// 实体类型
/// 图形数据库
/// 实体集合
/// ObjectId数组
public static ObjectId[] AddEntityToModelSpace(this Database db, ICollection entitys) where TEntity : Entity
///
/// 使用ObjectId来判断一个实体是否已经添加到图形数据库
///
/// 实体
/// 是否已添加到数据库
public static bool IsEntityInDatabase(this Entity entity)
///
/// 安全删除实体(处理锁定图层等情况)
///
/// 实体类型
/// 实体
/// 事务对象
public static void SafeEraseEntity(TEntity ent, Transaction tr) where TEntity : Entity
///
/// 设置实体颜色、图层
///
/// 实体类型
/// 实体
/// 颜色索引
/// 图层名字
public static void SetColorLayer(this TEntity entity, short colorIndex, string layerName) where TEntity : Entity
///
/// 设置多段线颜色、图层并闭合
///
/// 多段线
/// 颜色索引
/// 图层名字
/// 是否闭合
public static void SetPolylineColorLayer(this Polyline polyline, short colorIndex, string layerName, bool isClosed = true)
///
/// 设置实体的可见性(隐藏或显示)
///
/// 要操作的实体ID
/// 是否显示
/// 操作是否成功
public static bool SetEntityVisibility(ObjectId objectId, bool isVisible)
///
/// 隐藏指定实体
///
/// 实体ObjectId
/// 是否隐藏成功
public static bool HideEntity(this ObjectId objectId)
///
/// 显示指定实体
///
/// 实体ObjectId
/// 是否显示成功
public static bool ShowEntity(this ObjectId objectId)
///
/// 将ObjectId集合转换为Entity集合
///
/// 实体类型
/// ObjectId集合
/// 打开模式
/// 是否打开已删除对象
/// 实体集合
public static List ToEntities(this IEnumerable objectIds, OpenMode openMode = OpenMode.ForRead, bool openErased = false) where TEntity : Entity
///
/// 将Entity集合转换为ObjectId集合
///
/// 实体类型
/// 实体集合
/// ObjectId集合
public static List ToObjectIds(this IEnumerable entities) where TEntity : Entity
///
/// 将ObjectId集合转换为Entity集合(非泛型版本)
///
/// ObjectId集合
/// 打开模式
/// 是否打开已删除对象
/// 实体集合
public static List ToEntities(this IEnumerable objectIds, OpenMode openMode = OpenMode.ForRead, bool openErased = false)
}
///
/// 获取块的包围盒(.NET Framework 4.8 兼容版)
///
/// 实体
/// BlockBoxResult 包含包围盒和变换矩阵
public static BlockBoxResult GetBlockBox(this Entity entity)
///
/// 根据点集创建多段线
///
/// 点集合的类型,必须实现 IEnumerable 接口
/// 点集合,用于定义多段线的顶点位置
/// AutoCAD 数据库对象,用于确定多段线所属的数据库上下文
/// 多段线创建选项,包含线宽、颜色、图层等属性设置,可选参数
/// 自定义操作委托,可在多段线创建后执行额外操作,可选参数
/// 创建的多段线对象
/// 当 points 或 db 参数为 null 时抛出
/// 当 points 集合为空或包含不足2个点时抛出
///
/// 此方法为 IEnumerable 提供扩展方法,简化多段线创建流程。
/// 支持通过 options 参数统一设置多段线属性,通过 customAction 参数执行自定义逻辑。
/// 创建的多段线会自动添加到指定数据库的当前空间中。
///
public static Polyline CreatePolyline(this IEnumerable points, Database db ,
PolylineOptions options = null,
Action customAction = null)
}
```
##### Arc类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 圆弧工具类
///
public static class ArcTools
{
///
/// 计算两条平行圆弧之间的最短垂直距离
///
/// 第一条圆弧
/// 第二条圆弧
/// 几何容差(默认1e-5)
/// 圆弧间的最短垂直距离,若不平行返回double.NaN
[Obsolete("不稳定")]
public static double CalculateShortestDistanceBetweenParallelArcs(this Arc arc1, Arc arc2, double tolerance = 1e-5)
///
/// 判断两条圆弧是否平行且距离符合要求
///
/// 第一个圆弧
/// 第二个圆弧
/// 期望距离
/// 距离容差
/// 如果两条圆弧平行且距离在容差范围内返回true,否则返回false
public static bool AreArcsParallelAndAtDistance(this Arc arc1, Arc arc2,
double expectedDistance, double distanceTolerance)
///
/// 增强版平行距离判断(支持直线和圆弧)
///
/// 第一条墙线(直线或圆弧)
/// 第二条墙线(直线或圆弧)
/// 允许的距离数组
/// 距离容差(默认0.001)
/// 如果墙线平行且距离在允许范围内返回true,否则返回false
public static bool AreWallsParallelAndAtDistanceEnhanced(
this Curve wall1,
Curve wall2,
double[] allowedDistances,
double distanceTolerance = 0.001)
///
/// 判断两条直线是否平行且距离符合要求
///
/// 第一条直线
/// 第二条直线
/// 期望距离
/// 距离容差
/// 如果两条直线平行且距离在容差范围内返回true,否则返回false
public static bool AreLinesParallelAndAtDistance(Line line1, Line line2,
double expectedDistance, double distanceTolerance)
}
}
```
#### Curve类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 曲线工具类
///
public static class CurveTools
{
///
/// 安全获取曲线对象(全面检查对象有效性)
///
/// 当前事务
/// 要检查的曲线对象
/// 有效的曲线对象或null
public static Curve GetValidCurve(this Transaction tr, Curve curve)
///
/// 安全地计算曲线长度(解决 eInvalidOpenState 异常)
///
/// 曲线对象
/// 曲线长度
public static double GetLength(this Curve curve)
///
/// 尝试获取有效的曲线对象
///
/// 要检查的曲线对象
/// 当前事务
/// 有效的曲线对象或null
public static Curve TryGetValidCurve(this Curve curve, Transaction tr)
///
/// 安全的属性复制方法(不处理事务)
///
/// 源曲线对象
/// 目标曲线对象
public static void CopyCommonCurvePropertiesSafe(this Curve source, Curve target)
///
/// 检查实体是否可读
///
/// 要检查的实体
/// 如果实体可读返回true,否则返回false
private static bool IsEntityValidForRead(Entity entity)
///
/// 检查实体是否可写
///
/// 要检查的实体
/// 如果实体可写返回true,否则返回false
private static bool IsEntityValidForWrite(Entity entity)
///
/// 安全的XData复制
///
/// 源数据库对象
/// 目标数据库对象
private static void CopyXDataSafe(DBObject source, DBObject target)
///
/// 复制扩展数据(XData)
///
/// 源数据库对象
/// 目标数据库对象
private static void CopyXData(DBObject source, DBObject target)
///
/// 复制超链接(安全版本)
///
/// 源实体
/// 目标实体
private static void CopyHyperlinks(Entity source, Entity target)
///
/// 复制实体通用属性(更通用的方法)
///
/// 源实体
/// 目标实体
public static void CopyCommonProperties(this Entity source, Entity target)
}
}
```
##### Point类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 点工具类
///
public static class PointTools
{
///
/// 将3D点转换为2D点,忽略Z坐标
///
/// 要转换的3D点
/// 转换后的2D点
public static Point2d Point3dToPoint2d(this Point3d point3d)
///
/// 将2D点转换为3D点
///
/// 要转换的2D点
/// 转换后的3D点
public static Point2d Point2dToPoint3d(this Point2d point2d)
///
/// 获取2D点的中心点
///
/// 要获取中心的2D点
/// 中心点
public static Point2d GetPoint2dCenter(this Point2d point2d)
///
/// 获取3D点的中心点
///
/// 要获取中心的3D点
/// 中心点
public static Point3d GetPoint3dCenter(this Point3d point3d)
///
/// 获取两个点之间的中心点
///
/// 起点
/// 终点
/// 中点
public static Point3d GetCenterPointInTwoPointBetween(this Point3d startPoint, Point3d endPoint)
///
/// 获取从起点到终点的向量坐标
///
/// 起点坐标
/// 终点坐标
/// 向量坐标
public static Point3d GetPointArrivePointCoordinate(this Point3d startPoint, Point3d endPoint)
///
/// 获取两个3D点之间的中心点
///
/// 起点
/// 终点
/// 中心点
public static Point3d GetTwoPoint3dCenter(this Point3d start, Point3d end)
///
/// 获取两个2D点之间的中心点
///
/// 起点
/// 终点
/// 中心点
public static Point2d GetTwoPoint2dCenter(this Point2d start, Point2d end)
///
/// 获取与给定点指定角度和距离的点
///
/// 基点
/// 角度
/// 距离
/// 计算后的点
public static Point3d PolarPoint(this Point3d point, double angle, double dist)
///
/// 3D点转换为2D点
///
/// 3D点
/// 2D点
public static Point2d Point3dConvertToPoint2d(this Point3d point3d)
///
/// 判断三点是否在同一条直线上
///
/// 第一个点
/// 第二个点
/// 第三个点
/// 是否在同一条直线上
public static bool IsOnOneLine(this Point3d firstPoint, Point3d secondPoint, Point3d thirdPoint)
///
/// 计算两点中间点
///
/// 第一个点
/// 第二个点
/// 中间点
public static Point3d MidPoint(this Point3d p1, Point3d p2)
///
/// 判断两个点是否相等,考虑小数点误差
///
/// 第一个点
/// 第二个点
/// 误差范围
/// 是否相等
public static bool ArePointsEqual(this Point3d p1, Point3d p2, double epsilon)
///
/// 获得point X方向与point2的角度
///
/// 点1
/// 点2
/// 角度值
public static double GetAngleToXAxis(this Point3d point1, Point3d point2)
///
/// 获取两个点之间的中心点(整数坐标)
///
/// 起点
/// 终点
/// 中心点
public static Point3d GetCenterPointInTwoPointBetweenInt(this Point3d startPoint, Point3d endPoint)
///
/// 判断两个点是否相等(考虑距离误差)
///
/// 点1
/// 点2
/// 误差
/// 两个点是否相等
public static bool ArePointEquals(this Point3d point1, Point3d point2, double tolerance)
///
/// 检查四个点是否共面
///
/// 点数组
/// 是否共面
public static bool PointsAreCoplanar(Point3d[] points)
///
/// 点和点相加
///
/// 第一个点
/// 第二个点
/// 相加后的点
public static Point3d Add(this Point3d p1, Point3d p2)
///
/// 点坐标相减(返回新点)
///
/// 被减点
/// 减点
/// 坐标差的新点
public static Point3d Sub(this Point3d p1, Point3d p2)
///
/// 2D点和点相加
///
/// 第一个点
/// 第二个点
/// 相加后的点
public static Point2d Add(this Point2d p1, Point2d p2)
///
/// 2D点坐标相减(返回新点)
///
/// 被减点
/// 减点
/// 坐标差的新点
public static Point2d Sub(this Point2d p1, Point2d p2)
///
/// 测量两点之间的距离
///
/// 第一个点
/// 第二个点
/// 两点之间的距离
public static double MeasureDistance(Point3d point1, Point3d point2)
}
}
```
#### Polyline类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 多段线工具类
///
public static class PolylineTools
{
///
/// 计算两个平行多段线之间的距离
///
/// 第一条多段线
/// 第二条多段线
/// 距离值
public static double GetDistanceBetweenParallelPolylines(this Polyline pl1, Polyline pl2)
///
/// 复制多段线属性
///
/// 源多段线
/// 目标多段线
public static void CopyPolylineProperties(this Polyline source, Polyline target)
///
/// 隐藏图框内部实体
///
/// 图框多段线
/// 事务对象
/// 块表记录
/// 是否可见
public static void VisibleEntitiesInsideFrame(this Polyline frame, Transaction tr, BlockTableRecord btr, bool isVisible = false)
///
/// 检查一个边界框是否完全包含另一个边界框
///
/// 外部边界框
/// 内部边界框
/// 是否包含
public static bool ContainsExtents(Extents3d outer, Extents3d inner)
///
/// 检查实体是否在多段线内部
///
/// 要检查的实体
/// 多段线图框
/// 是否在多段线内部
public static bool IsEntityInsidePolyline(Entity ent, Polyline pl)
///
/// 使用射线法检查点是否在多段线内部
///
/// 要检查的点
/// 多段线
/// 点是否在多段线内部
public static bool IsPointInsidePolyline(Point3d point, Polyline pl)
///
/// 创建中心线
///
/// 第一条多段线
/// 第二条多段线
/// 距离容差
/// 中心线列表
public static List CreateCenterLineByExploding(this Polyline pline1, Polyline pline2, double distanceTolerance)
///
/// 计算两条平行圆弧的中线
///
/// 第一条圆弧
/// 第二条圆弧
/// 中线圆弧
private static Arc CalculateArcCenterLine(Arc arc1, Arc arc2)
///
/// 处理直线对
///
/// 第一条直线
/// 第二条直线
/// 中心多段线
/// 是否为首段
/// 距离容差
private static void ProcessLinePair(Line line1, Line line2, Polyline centerPline, bool isFirstSegment, double distanceTolerance)
///
/// 计算两条平行直线的中线
///
/// 第一条直线
/// 第二条直线
/// 距离容差
/// 中线直线
private static Line CalculateLineCenterLine(Line line1, Line line2, double distanceTolerance)
///
/// 获取两条平行直线两侧的端点对
///
/// 第一条直线
/// 第二条直线
/// 端点对元组
public static Tuple, Tuple> GetBothSideEndPoints(Line line1, Line line2)
///
/// 获取点在直线上的投影点
///
/// 直线
/// 点
/// 投影点
private static Point3d GetProjectionPoint(Line line, Point3d point)
///
/// 分解多段线为线段
///
/// 多段线
/// 线段列表
private static List ExplodePolyline(Polyline pline)
///
/// 复制属性
///
/// 源多段线
/// 目标多段线
private static void CopyProperties(Polyline source, Polyline target)
}
}
```
##### Editor类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 编辑器工具类
///
public static class EditorTools
{
///
/// 将AutoCAD编辑器的视图缩放到指定的3D范围
///
/// AutoCAD编辑器对象
/// 要缩放的3D范围
public static void Zoom(this Editor ed, Extents3d ext)
///
/// 缩放至全部范围
///
/// AutoCAD编辑器对象
public static void ZoomExtents(this Editor ed)
///
/// 选择一个实体
///
/// 编辑器对象
/// 提示信息
/// 实体类型
/// 实体ObjectId
public static ObjectId GetEntity_(this Editor ed, string message, Type type = null)
///
/// 获取选择集
///
/// 编辑器对象
/// 提示信息
/// 实体ObjectId列表
public static List GetSelection_(this Editor ed, string message)
///
/// 选择一个点
///
/// 编辑器对象
/// 选择的3D点
public static Point3d GetPoint(this Editor ed)
///
/// 选择所有线
///
/// 编辑器对象
/// 直线列表
public static List SelectAllLines(this Editor ed)
///
/// 选择一个点
///
/// 编辑器对象
/// 提示信息
/// 选择的3D点
public static Point3d GetPoint3d(this Editor ed, string prompt)
///
/// 选择一个点
///
/// 编辑器对象
/// 提示信息
/// 选择的3D点
public static Point3d GetPoint2(this Editor ed, string prompt)
///
/// 选择实体(只选择线和多段线)并可选择过滤图层
///
/// AutoCAD编辑器对象
/// 提示信息
/// 图层名称
/// 是否允许多选
/// 用户选择的对象ID数组
public static ObjectId[] GetSelectionLineAndPolyLine(this Editor ed, string message, string layerName = "", bool allowMultiple = true)
///
/// 选择实体(只选择线和多段线)并支持多个图层过滤
///
/// AutoCAD编辑器对象
/// 提示信息
/// 图层名称数组
/// 是否允许多选
/// 用户选择的对象ID数组
public static ObjectId[] GetSelectionLineAndPolyLine(this Editor ed, string message, string[] layerNames, bool allowMultiple = true)
///
/// 选择实体并返回实体对象列表
///
/// AutoCAD编辑器对象
/// 提示信息
/// 图层名称
/// 事务对象
/// 实体对象列表
public static List GetSelectionLineAndPolyLineEntities(this Editor ed, string message, string layerName, Transaction transaction)
///
/// 选择单个实体
///
/// AutoCAD编辑器对象
/// 提示信息
/// 图层名称
/// 选择的实体ObjectId
public static ObjectId GetSingleSelectionLineOrPolyLine(this Editor ed, string message, string layerName = "")
///
/// 获取圆和圆弧
///
/// 当前文档
/// 对象ID数组
public static ObjectId[] SelectAllCircleArcs(this Document doc)
///
/// 获取圆和圆弧的中心点和半径
///
/// 当前文档
/// 对象ID数组
/// 中心点与半径的字典
public static Dictionary GetCircleArcCenterRadius(this Document doc, ObjectId[] objectIds)
///
/// 获取圆和圆弧中心点和半径
///
/// 文档对象
/// 对象ID数组
/// 事务对象
/// 点比较容差
/// 中心点与半径的字典
public static Dictionary GetCircleArcCenterRadius(this Document doc, ObjectId[] objectIds, Transaction trans, double tolerance = 0.001)
///
/// 获取直线
///
/// 当前文档
/// 直线列表
public static List SelectLines(this Document doc)
///
/// 获取直线ID
///
/// 当前文档
/// 直线ObjectId列表
public static List SelectLineIds(this Document doc)
///
/// 获取指定图层上的多段线
///
/// 当前文档
/// 事务对象
/// 图层名称
/// 多段线ObjectId列表
public static List GetPolylineBySelectAndLayerName(this Document doc, Transaction trans, string layerName)
///
/// 获取圆
///
/// 当前文档
/// 圆列表
public static List SelectCircles(this Document doc)
///
/// 输入过滤类型,获得选择集
///
/// 过滤类型
/// 选择集
public static SelectionSet GetSelectionEx(TypedValue[] type = null)
///
/// 获取选择集
///
/// 选择集
public static SelectionSet PickFirst()
///
/// 选择所有实体
///
/// 编辑器对象
/// 选择过滤器
/// 实体ObjectId列表
public static List SelectAll_(this Editor ed, SelectionFilter filter = default)
///
/// 获得用户输入的双精度浮点数
///
/// 提示信息
/// 默认值
/// 用户输入的值
public static double GetUserDouble(this string message, double defaultvalue = 0.0)
///
/// 获得用户输入的双精度浮点数
///
/// 编辑器对象
/// 提示信息
/// 默认值
/// 用户输入的值
public static double GetUserDouble(this Editor ed, string message, double defaultvalue = 0.0)
///
/// 获取用户是否删除源对象的选择
///
/// 编辑器对象
/// 默认选择
/// 用户选择
public static bool GetEraseSourceChoice(this Editor ed, bool defaultChoice = false)
///
/// 获得用户输入的是或否选择
///
/// 编辑器对象
/// 提示信息
/// 默认选择
/// 用户选择
public static bool? GetUserYesOrNo(this Editor ed, string prompt = "\n是或否?[是(Y)/否(N)]", bool defaultChoice = false)
///
/// 获取CAD鼠标当前位置坐标
///
/// 命令栏
/// 坐标(可能为null)
public static Point3d? GetCurrentMouthPoint(this Editor ed)
///
/// 获得用户输入的字符串
///
/// 提示信息
/// 用户输入的字符串
public static string GetUserMessage(this string message)
///
/// 获得用户输入的字符串
///
/// 提示信息
/// 用户输入的字符串
public static string GetUserStr(this string message)
///
/// 获得用户输入的点
///
/// 提示信息
/// 用户输入的点
public static Point3d? GetPoint(this string message)
///
/// 选择点
///
/// 编辑器对象
/// 提示信息
/// 选择的点
public static Point3d GetPoint_(this Editor ed, string message)
///
/// 获取用户输入的角度值
///
/// 编辑器对象
/// 提示信息
/// 默认角度值
/// 是否使用角度制
/// 是否允许不输入
/// 角度值
public static double? GetAngleFromUser(this Editor ed, string promptMessage = "\n请输入角度:", double? defaultValue = null, bool useDegrees = true, bool allowNone = true)
///
/// 获取用户输入的角度值(带范围验证)
///
/// 编辑器对象
/// 提示信息
/// 最小值
/// 最大值
/// 默认角度值
/// 是否使用角度制
/// 角度值
public static double? GetAngleInRange(this Editor ed, string promptMessage = "\n请输入角度:", double minValue = 0, double maxValue = 2 * Math.PI, double? defaultValue = null, bool useDegrees = true)
///
/// 通过两点获取角度
///
/// 基点
/// 提示信息
/// 角度值
public static double? GetAngleByTwoPoints(Point3d basePoint, string promptMessage = "\n指定角度方向:")
///
/// 通过过滤器获取实体
///
/// 编辑器对象
/// 过滤类型
/// 选择集
public static SelectionSet GetSelectionEntity(this Editor ed, TypedValue[] type = null)
///
/// 通过过滤器获取实体
///
/// 编辑器对象
/// 选择集
public static SelectionSet SelectSet(this Editor ed)
///
/// 刷新当前文档视图
///
/// 要刷新的文档对象
public static void RefreshView(this Document document)
///
/// 缩放至全部范围
///
/// 要操作的文档对象
public static void ZoomExtents(this Document document)
}
}
```
##### Layer类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 图层工具类
///
public static class LayerTools
{
///
/// 获取图层名
///
/// 事务对象
/// 文档对象
/// 图层名字列表
public static List GetAllLayerName(this Transaction trans, Document doc)
///
/// 创建一个新的图层
///
/// 图形数据库
/// 图层名
/// 新添加的层表记录的ObjectId
public static ObjectId AddLayer(this Database db, string layerName)
///
/// 添加图层
///
/// 图层名
/// 图层颜色索引
public static void AddLayer(this string layName, int Index)
///
/// 修改指定图层的颜色
///
/// 图形数据库
/// 图层名
/// 颜色索引值
/// 设置图层是否成功
public static bool SetLayerColor(this Database db, string layerName, short colorIndex)
///
/// 获取当前图形中所有的图层
///
/// 图形数据库
/// 所有图层记录表
public static List GetAllLayers(this Database db)
///
/// 删除指定名称的图层
///
/// 图形数据库
/// 要删除的图层名
/// 是否删除成功
public static bool DeleteLayer(this Database db, string layerName)
///
/// 批量删除图层
///
/// 图形数据库
/// 要删除的图层名称数组
/// 成功删除的图层数量
public static int DeleteLayers(this Database db, params string[] layerNames)
///
/// 删除所有空图层
///
/// 图形数据库
/// 成功删除的图层数量
public static int DeleteAllEmptyLayers(this Database db)
///
/// 解锁指定图层(仅当前事务有效)
///
/// 文档对象
/// 图层名称
/// 是否解锁成功
public static bool UnlockByLayer(this Document doc, string layerName)
///
/// 锁定指定图层
///
/// 文档对象
/// 要锁定的图层名称数组
/// 成功锁定的图层数量
public static int LockLayers(this Document doc, params string[] layerNames)
///
/// 锁定单个图层
///
/// 文档对象
/// 要锁定的图层名称
/// 是否成功锁定
public static bool LockLayer(this Document doc, string layerName)
///
/// 通过交互选择锁定图层
///
/// 文档对象
/// 成功锁定的图层数量
public static int LockLayersInteractive(this Document doc)
///
/// 锁定所有图层
///
/// 文档对象
/// 成功锁定的图层数量
public static int LockAllLayers(this Document doc)
///
/// 获取所有图层名称
///
/// 文档对象
/// 图层名称列表
public static List GetAllLayerName(this Document doc)
///
/// 设置指定实体的图层名称和颜色
///
/// 实体类型
/// 实体对象
/// 图层名称
/// 红色分量
/// 绿色分量
/// 蓝色分量
/// 事务对象
/// 文档对象
public static void SetLayer(this TEntity entity, string layerName, byte red, byte green, byte blue, Transaction trans, Document doc) where TEntity : Entity
///
/// 解锁指定图层
///
/// 文档对象
/// 图层名称
/// 操作是否成功
public static bool UnlockLayer(this Document document, string layerName)
///
/// 设置实体图层和颜色
///
/// 实体类型
/// 实体对象
/// 文档对象
/// 图层名称
/// 红色分量
/// 绿色分量
/// 蓝色分量
public static void SetLayer(this TEntity entity, Document doc, string layerName, byte red = 255, byte green = 0, byte blue = 0) where TEntity : Entity
///
/// 检查指定图层上的所有实体中是否至少有一个是参考块
///
/// 图层名称
/// 如果至少有一个实体是参考块,则返回true;否则返回false
public static bool HasBlockReferenceOnLayer(this string layerName)
///
/// 通过图层名称选择实体
///
/// 文档对象
/// 图层名称数组
/// 选择提示信息
/// 是否允许不选择任何对象
/// 选择结果
public static ObjectId[] SelectEntitiesByLayer(this Document doc, string[] layerNames, string message = "\n选择对象:", bool allowNone = false)
///
/// 创建基于图层名称的选择过滤器
///
/// 图层名称数组
/// 选择过滤器
public static SelectionFilter GetSelectionFilterByLayerName(params string[] layerNames)
///
/// 设置实体图层和颜色
///
/// 实体对象
/// 图层名称
public static void SetDimensionEntityLayerAndColor(this Entity entity, string layerName)
///
/// 设置实体图层和颜色
///
/// 实体类型
/// 实体列表
/// 图层名称
public static void SetEntityLayerAndColor(this List entitys, string layerName) where TEntity : Entity
///
/// 更改指定实体的图层名称
///
/// 实体对象
/// 图层名称
public static void ChangeEntityLayer(this Entity entity, string layerName)
///
/// 生成随机的ACI颜色索引(排除0和7)
///
/// 颜色索引
public static short GetRandomColorIndex()
///
/// 生成随机的深色ACI索引(适用于白底显示)
///
/// 颜色索引
public static short GetRandomDarkColorIndex()
///
/// 显示指定图层上的所有实体
///
/// 图层名称
/// 文档对象
public static void ShowAllEntitiesOnLayer(string layerName, Document doc)
///
/// 获取指定图层上的所有实体
///
/// 图层名称
/// 文档对象
/// 实体列表
public static List GetAllEntitiesOnLayer(string layerName, Document doc)
///
/// 显示所有图层
///
public static void ShowAllLayers()
///
/// 隐藏除选中实体所在图层外的所有图层
///
public static void HideOtherLayers()
}
}
```
##### Block类扩展
``` CSharp
namespace AutoCAD.EntityTool
{
///
/// 块工具类
///
public static class BlockTools
{
///
/// 创建一个块并添加到数据库中
///
/// 图形数据库
/// 块名
/// 实体列表
/// 块表记录的Id,失败返回ObjectId.Null
public static ObjectId AddBlockTableRecord(this Database db, string blockName, List ents)
///
/// 检查实体是否适合添加到块中
///
/// 要检查的实体
/// 目标数据库
/// 如果实体适合添加到块中返回true,否则返回false
private static bool IsEntityValidForBlock(Entity entity, Database targetDb)
///
/// 检查块名称是否有效
///
/// 要检查的块名称
/// 如果块名称有效返回true,否则返回false
private static bool IsValidBlockName(string blockName)
///
/// 检查实体是否有效
///
/// 要检查的实体
/// 如果实体有效返回true,否则返回false
private static bool IsEntityValid(Entity entity)
///
/// 检查实体是否有效(替代方法)
///
/// 要检查的实体
/// 如果实体有效返回true,否则返回false
private static bool IsEntityValid2(Entity entity)
///
/// 从当前选择集创建块
///
/// 图形数据库
/// 块名
/// 基点
/// 块表记录的Id,失败返回ObjectId.Null
public static ObjectId CreateBlockFromSelection(this Database db, string blockName, Point3d basePoint)
///
/// 创建带有属性的块
///
/// 图形数据库
/// 块名
/// 实体列表
/// 属性字典
/// 块表记录的Id,失败返回ObjectId.Null
public static ObjectId AddBlockWithAttributes(this Database db, string blockName, List ents, Dictionary attributes)
///
/// 重载AddBlockTableRecord扩展函数,使其能接受不固定的实体对象
///
/// 图形数据库
/// 块名
/// 实体数组
/// 块表记录的Id
public static ObjectId AddBlockTableRecord(this Database db, string blockName, params Entity[] ents)
///
/// 在CAD图形中插入参照块
///
/// 表示块参照要加入的模型空间或图纸空间的Id
/// 块参照要加入的图层名
/// 块参照所属的块名
/// 插入点
/// 缩放比例
/// 旋转角度
/// 实体Id
public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle = 0)
///
/// 块参照添加属性实体
///
/// 块表记录Id
/// 要加入的块属性列表
public static void AddAttributeToBlock(this ObjectId blockId, List atts)
///
/// 重载AddAttributeToBlock扩展函数,使其能接受不固定的属性定义对象
///
/// 块表记录Id
/// 属性定义数组
public static void AddAttributeToBlock(this ObjectId blockId, params AttributeDefinition[] atts)
///
/// CAD图形中插入带属性的块参照
///
/// 块参照要加入的模型空间或图纸空间的Id
/// 块参照要加入的图层名
/// 块参照所属的块名
/// 插入点
/// 缩放比例
/// 旋转角度
/// 表示属性的名称与取值
/// 实体Id
public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle, Dictionary attNameValues)
///
/// 更新块参照中的属性值
///
/// 块参照Id
/// 需要更新的属性名称与取值
/// 事务对象(可选)
public static void UpdateAttributeInBlock(this ObjectId blockRefId, Dictionary attNameValues, Transaction transaction = null)
///
/// 更新块属性选项
///
public class UpdateAttributeOptions
///
/// 增强版:更新块参照中的属性值
///
/// 块参照Id
/// 需要更新的属性名称与取值
/// 更新选项
/// 如果更新成功返回true,否则返回false
public static bool UpdateAttributesInBlock(this ObjectId blockRefId, Dictionary attNameValues, UpdateAttributeOptions options = null)
///
/// 设置属性定义的通用样式
///
/// 属性定义
/// 属性文字的可见性
public static void SetStyleForAtt(this AttributeDefinition att, bool invisible)
///
/// 读取块中的属性值
///
/// 图形数据库
/// 块名
/// 属性字典
public static Dictionary ReadDataInBlock(this Database db, string blockName)
///
/// 获取动态块的动态属性值
///
/// 动态块的ObjectId
/// 需要查找的动态属性名
/// 动态属性值
public static string GetDynamicBlockValue(this ObjectId blockId, string propName)
///
/// 获取动态块的动态属性值
///
/// 图形数据库
/// 块名
/// 需要查找的动态属性名
/// 动态属性值
public static string GetDynamicBlockValue(this Database db, string blockName, string propName)
///
/// 获得动态块的所有动态属性
///
/// 动态块的ObjectId
/// 动态属性集合
public static DynamicBlockReferencePropertyCollection GetDynProperties(this ObjectId blockId)
///
/// 设置动态块的动态属性
///
/// 动态块的ObjectId
/// 动态属性的名称
/// 动态属性的值
public static void SetDynamicBlockValue(this ObjectId blockId, string propName, object value)
///
/// 获取特定类型的所有实体
///
/// 实体类型
/// 图形数据库
/// 打开模式
/// 是否打开已删除的实体
/// 类型为T的实体列表
public static List GetEntsInDatabase(this Database db, OpenMode mode, bool OpenErased) where T : Entity
///
/// 只需要以读的方式获取数据库中特定类型的实体
///
/// 实体类型
/// 图形数据库
/// 实体列表
public static List GetEntsInDatabase(this Database db) where T : Entity
///
/// 获取特定类型(模型空间中)的所有实体
///
/// 实体类型
/// 图形数据库
/// 打开模式
/// 是否打开已删除的实体
/// 类型为T的实体列表
public static List GetEntsInModelSpace(this Database db, OpenMode mode, bool OpenErased) where T : Entity
///
/// 获取特定类型(模型空间中)的所有实体
///
/// 块参照类型
/// 图形数据库
/// 打开模式
/// 是否打开已删除的实体
/// 类型为T的实体列表
public static List GetEntsInModelSpaces(this Database db, OpenMode mode, bool OpenErased) where T : BlockReference
///
/// 获取特定类型的所有实体
///
/// 实体类型
/// 图形数据库
/// 打开模式
/// 是否打开已删除的实体
/// 类型为T的实体列表
public static List GetSelections(this Database db, OpenMode mode, bool OpenErased) where T : Entity
///
/// 获取动态块/非动态块的块名
///
/// 块参照对象
/// 返回块名字符串,如果块参照不存在则返回null
public static string GetBlockName(this BlockReference bref)
///
/// 动态块的读取(DWG)
///
/// DWG文件名
/// 动态块名
public static void InitialZwBlockReference(this string blockDWGName, string blockName)
///
/// 根据想要显示的值去显示
///
/// 块参照对象
/// 块名
public static void CheckBlockPropertyValue(this BlockReference br, string blockName)
///
/// 修改动态块属性
///
/// 动态块名
/// 修改的属性名
/// 修改的属性值
/// 事务
public static void ModifyDynamicBlockParameter(this string blockName, string paramName, object paramValue, Transaction trans)
///
/// 从外部文件导入块
///
/// 目标数据库
/// 包含完整路径的外部文件名
public static void ImportBlocksFromDwg(this Database destDb, string sourceFileName)
///
/// 找到自定义属性的类型
///
/// 文档
/// 块名
public static void GetPropType(this Document doc, string blockName)
///
/// 动态块个数
///
/// 当前文档
/// 实体数量
public static double RecursionBlock(this Document doc)
///
/// 递归块引用
///
/// 块参照
/// 实体列表
private static List GetBlockEntity(this BlockReference refblock)
///
/// 插入一个块
///
/// 文档
/// 提示消息
/// 如果插入成功返回true,否则返回false
public static bool InsertBlock(this Document doc, string message = "请输入块名称")
///
/// 创建一个块
///
/// 当前文档
/// 提示信息
/// 实体
public static Entity CreateBlock(this Document doc, string message)
}
}
```
##### Line类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 直线工具类
///
public static class LineTools
{
///
/// 判断多段线是否为矩形
///
/// 多段线对象
/// 如果是矩形返回true,否则返回false
public static bool IsRectangle(Polyline pl)
///
/// 判断多段线是否为矩形(优化版)
///
/// 多段线对象
/// 如果是矩形返回true,否则返回false
public static bool IsRectanglePolyline(Polyline pl)
///
/// 获取直线长度
///
/// 直线对象
/// 直线长度
public static double GetLineLength(this Line line)
///
/// 计算两条平行线之间的最短距离
///
/// 第一条直线
/// 第二条直线
/// 几何容差
/// 最短距离,如果不平行返回double.NaN
public static double CalculateShortestDistanceBetweenParallelLines(this Line line1, Line line2, double tolerance)
///
/// 检查直线相交并在相交处裁剪两条线的短边(仅当短边有长度时)
///
/// 文档对象
/// 直线ObjectId列表
public static void TrimValidShortSidesAtIntersections(this Document doc, List lineIds)
///
/// 计算两条平行曲线之间的中线(支持不等长情况)
///
/// 第一条曲线
/// 第二条曲线
/// 距离容差
/// 中线列表(可能包含多条线段)
public static List CalculateCenterLines(this Curve curve1, Curve curve2, double distanceTolerance)
///
/// 计算两条平行直线的中线(优化版)
///
/// 第一条直线
/// 第二条直线
/// 距离容差
/// 中线对象,如果输入无效则返回null
public static Line CalculateLineCenterLine(Line line1, Line line2, double distanceTolerance)
///
/// 获取点在直线上的投影点
///
/// 直线对象
/// 要投影的点
/// 投影点
public static Point3d GetProjectionPoint(Line line, Point3d point)
}
}
```
#### Exception类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 异常处理工具类
///
public static class ExceptionTools
{
///
/// 处理异常
///
/// 异常对象
/// 发生错误的函数名
public static void HandleEntityToolErrorSend(this Exception ex, string errorFunction)
///
/// 处理实体工具异常
///
/// 异常对象
/// 发生错误的函数名
/// 是否显示警报对话框
/// 是否记录到Trace
public static void HandleEntityToolError(this Exception ex, string errorFunction, bool showAlert = true, bool logToTrace = true)
///
/// 构建错误消息
///
/// 异常对象
/// 发生错误的函数名
/// 格式化后的错误消息
public static string BuildErrorMessage(this Exception ex, string errorFunction)
///
/// 输出到CAD消息
///
/// 错误消息
/// 异常对象
public static void OutputToCadMessages(this string errorMessage, Exception ex)
///
/// 显示警报消息
///
/// 异常对象
/// 发生错误的函数名
public static void ShowAlertMessage(this Exception ex, string errorFunction)
///
/// 获取用户友好的错误消息
///
/// 异常对象
/// 用户友好的错误消息
public static string GetUserFriendlyMessage(this Exception ex)
///
/// 记录到Trace
///
/// 异常对象
/// 错误消息
public static void LogToTrace(this Exception ex, string errorMessage)
///
/// 记录到Windows事件日志
///
/// 异常对象
public static void LogToEventLog(this Exception ex)
///
/// 处理异常处理程序本身的异常
///
/// 异常处理程序抛出的异常
public static void HandleHandlerException(this Exception handlerEx)
///
/// 简化的异常处理扩展方法
///
/// 异常对象
/// 上下文信息
public static void HandleSimple(this Exception ex, string context = null)
}
}
```
#### Dimension扩展
``` CSharp
///
/// 在曲线上创建建筑样式长度标注
///
/// 曲线
/// database
/// 曲线长度标注选项
/// 返回
///
public static AlignedDimension CreateLengthDimension(this Curve curve,Database db,
LengthDimensionOptions options = null)
///
/// 曲线长度标注选项
///
public class LengthDimensionOptions
{
/// 文字前缀(如:长度、L=等)
public string TextPrefix { get; set; } = "";
/// 文字后缀
public string TextSuffix { get; set; } = "";
/// 文字位置
public DimensionTextPosition TextPosition { get; set; } = DimensionTextPosition.Above;
/// 标注样式名
public string DimensionStyle { get; set; } = "Standard";
/// 基础文字高度
public double BaseTextHeight { get; set; } = 2.0;
/// 基础延伸线长度
public double BaseExtensionLength { get; set; } = 1.5;
/// 箭头大小比例
public double ArrowSizeScale { get; set; } = 1.0;
public int ColorIndex { get; set; } = 3;
/// 标注偏移距离(相对于曲线)
public double OffsetDistance { get; set; } = 10.0;
}
```
#### String类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 字符串工具类
///
public static class StringTools
{
///
/// 将Point3d转换为标准坐标字符串 (X,Y,Z)
///
/// 三维点
/// 小数位数(默认3位)
/// 格式化的坐标字符串
public static string ToCoordinateString(this Point3d point, int decimalPlaces = 3)
///
/// 将Point2d转换为标准坐标字符串 (X,Y)
///
/// 二维点
/// 小数位数(默认3位)
/// 格式化的坐标字符串
public static string ToCoordinateString(this Point2d point, int decimalPlaces = 3)
///
/// 处理字符串中的换行符
///
/// 输入字符串
/// 处理后的字符串
public static string ProcessNewLines(this string input)
///
/// 从字符串解析Point3d (支持X,Y,Z或X,Y格式)
///
/// 坐标字符串
/// 解析后的Point3d
public static Point3d ParsePoint3d(string coordString)
///
/// 获取点的X坐标字符串
///
/// 三维点
/// 小数位数
/// X坐标字符串
public static string GetXString(this Point3d point, int decimalPlaces = 3)
///
/// 获取点的Y坐标字符串
///
/// 三维点
/// 小数位数
/// Y坐标字符串
public static string GetYString(this Point3d point, int decimalPlaces = 3)
///
/// 获取点的Z坐标字符串
///
/// 三维点
/// 小数位数
/// Z坐标字符串
public static string GetZString(this Point3d point, int decimalPlaces = 3)
///
/// 将点转换为WKT(Well-Known Text)格式
///
/// 三维点
/// WKT格式字符串
public static string ToWktString(this Point3d point)
///
/// 将点转换为JSON格式
///
/// 三维点
/// JSON格式字符串
public static string ToJsonString(this Point3d point)
///
/// 计算两点之间的距离
///
/// 第一个点
/// 第二个点
/// 两点之间的距离
public static double DistanceTo(this Point3d point1, Point3d point2)
///
/// 将Point3d转换为Point2d(丢弃Z坐标)
///
/// 三维点
/// 二维点
public static Point2d ToPoint2d(this Point3d point)
///
/// 将Point2d转换为Point3d(Z坐标设为0)
///
/// 二维点
/// 三维点
public static Point3d ToPoint3d(this Point2d point)
}
}
```
##### Double类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 双精度浮点数工具类
///
public static class DoubleTools
{
///
/// 检查两个双精度浮点数是否在指定的误差范围内几乎相等
///
/// 第一个双精度浮点数
/// 第二个双精度浮点数
/// 差值
/// 最大绝对误差
/// 如果两个数在误差范围内几乎相等返回true,否则返回false
public static bool AlmostEqualNorm(this double a, double b, double diff, double maximumAbsoluteError)
///
/// 检查两个双精度浮点数是否在指定的误差范围内几乎相等
///
/// 第一个双精度浮点数
/// 第二个双精度浮点数
/// 最大绝对误差
/// 如果两个数在误差范围内几乎相等返回true,否则返回false
public static bool AlmostEqual(this double a, double b, double maximumAbsoluteError)
///
/// 检查双精度浮点数是否在指定的误差范围内接近零
///
/// 要检查的数值
/// 误差范围
/// 如果数值在误差范围内接近零,则返回true;否则返回false
public static bool IsZero(this double value, double epsilon)
///
/// 将字符串解析为整数,如果解析失败则返回默认值
///
/// 要解析的字符串
/// 默认值
/// 解析后的整数值或默认值
public static int ParseToIntOrDefault(this string input, int defaultValue = 0)
}
}
```
#### Text类扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 文字工具类
///
public static class TextTools
{
///
/// 在指定位置插入文字(支持颜色和字号)
///
/// 文档对象
/// 插入点坐标
/// 颜色索引(ACI颜色)
/// 文字内容
/// 文字高度
/// 图层名(可选)
/// 插入的文字ObjectId
public static ObjectId InsertText(this Document doc, Point3d position, short colorIndex, string text, double textHeight, string layerName = "0")
///
/// 批量插入文字(高性能版)
///
/// 文档对象
/// 位置集合
/// 颜色索引
/// 文字内容集合
/// 文字高度
/// 插入的文字ObjectId列表
public static List InsertTexts(this Document doc, IEnumerable positions, short colorIndex, IEnumerable texts, double textHeight)
///
/// 在指定位置插入文字(支持颜色和字号)
///
/// 位置
/// 文字内容
/// 图层名
/// 颜色索引
/// 文字高度
/// 多行文字对象
public static MText InsertText(this Point3d location, string msg, string layerName, int colorIndex = 4, double height = 350)
///
/// 在指定位置显示文字
///
/// 位置
/// 信息索引
/// 文字高度
/// 多行文字对象
public static MText ShowText(this Point3d location, int i, double height = 80)
}
}
```
#### ShowMessage扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 消息显示工具类
///
public static class ShowMessageTools
{
///
/// 弹窗提示
///
/// 提示字符
public static void CadAlert(this string str)
///
/// 命令行提示
///
/// 提示字符
public static void CadMessage(this string str)
///
/// 命令行提示
///
/// 提示字符
public static void CadMessage2(this string str)
///
/// 命令行提示操作结果
///
/// 操作是否成功
/// 操作名称
public static void CadMessage(this bool isSuccess, string operation)
///
/// EntityTool对话框
///
/// 输出信息
public static void EntityToolMessage(this string message)
///
/// 显示进度条
///
/// 提示消息
/// 更新进度条后的延迟时间(毫秒)
/// 实体数组
public static void ShowProgressBar(this string showMessage, int time = 100, params TEntity[] entities) where TEntity : Entity
}
}
```
#### Unit扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 单位转换工具类
///
public static class UnitTools
{
///
/// 角度转弧度
///
/// 角度
/// 弧度
public static double DegreeToAngle(this double degree)
///
/// 弧度转角度
///
/// 弧度
/// 角度
public static double AngleToDegree(this double angle)
}
}
```
#### Vector扩展
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// 向量工具类
///
public static class VectorTools
{
}
///
/// 向量比较器(考虑容差)
///
public class VectorEqualityComparer : IEqualityComparer
{
private readonly double _tolerance;
///
/// 构造函数
///
/// 容差值
public VectorEqualityComparer(double tolerance)
///
/// 比较两个向量是否相等(考虑容差)
///
/// 第一个向量
/// 第二个向量
/// 如果向量相等返回true,否则返回false
public bool Equals(Vector3d v1, Vector3d v2)
///
/// 获取向量的哈希码
///
/// 向量对象
/// 哈希码
public int GetHashCode(Vector3d obj)
}
}
```
#### CadFileOperation
``` CSharp
namespace AutoCAD.EntityTools
{
///
/// CAD文件操作工具类
///
public static class CadFileOperationTools
{
///
/// 保存当前图形
///
/// 当前文档
public static void SaveCurrentDrawing(this Document doc)
///
/// 另存当前图形
///
/// 当前文档
public static void SaveDrawingAs(this Document doc)
///
/// 导出选定对象到新文件
///
/// 要导出的对象ID列表
/// 目标文件路径
public static void ExportObjectsToFile(this List objectIds, string filePath)
///
/// 导出选定对象到新文件(带交互选择)
///
/// 当前文档
public static void ExportSelectedObjects(this Document doc)
///
/// 创建新图纸
///
/// 当前文档
public static void CreateNewDrawing(this Document doc)
}
}
```
#### Ribbon封装类调用示例
``` CSharp
namespace AutoCAD.EntityTool.Tests
{
///
/// 测试功能的Ribbon命令实现
///
public class TestRibbonCommand : RibbonCommand
{
public RelayCommand RunCommand { get; set; }
public RelayCommand InsertTextTestCommand { get; set; }
public RelayCommand CadAlertTestCommand { get; set; }
public TestRibbonCommand()
{
InitializeCommands();
}
///
/// 初始化命令
///
private void InitializeCommands()
{
RunCommand = new RelayCommand(() => SendCommand(nameof(Demo.Run)));
InsertTextTestCommand = new RelayCommand(() => SendCommand(nameof(TextToolsTest.InsertTextTest)));
CadAlertTestCommand = new RelayCommand(() => SendCommand(nameof(ShowMessageToolsTest.CadAlertTest)));
}
///
/// 重写获取命令的方法
///
public override ICommand GetCommand(string commandName)
{
switch (commandName)
{
case "RunCommand": return RunCommand;
case "InsertTextTestCommand": return InsertTextTestCommand;
case "CadAlertTestCommand": return CadAlertTestCommand;
default: return null;
}
}
}
///
/// 测试功能的Ribbon构建器
///
public class TestRibbonBuilder : RibbonBuilderBase
{
public TestRibbonBuilder() : base()
{
}
///
/// 重写初始化配置
///
protected override void InitializeDefaults()
{
// 自定义配置
_tabId = "_TestTab";
_tabTitle = "测试功能区";
_configXmlPath = Path.Combine(ConfigPath._ProfilePath2, "TestConfig.xml");
//_iconsBasePath = Path.Combine(ConfigPath.AssemblyRunRootPath, "TestIcons");
_iconsBasePath = Path.Combine(ConfigPath.AssemblyRunRootPath);
// 自定义面板
_panelConfigs.Clear();
_panelConfigs.Add(new PanelConfig { Title = "测试工具", Orientation = Orientation.Vertical });
// 初始化命令
_ribbonCommand = new TestRibbonCommand();
}
///
/// 重写命令获取方法
///
protected override ICommand GetCommand(string commandName)
{
// 可以在这里添加自定义的命令映射
return base.GetCommand(commandName);
}
///
/// 重写按钮创建方法
///
protected override void CreateButton(ICommand command, string text, string image,
out RibbonButton button, string expandimgPath, string commandName, string title,
string content, string expandcontent, Orientation orientation = Orientation.Horizontal)
{
base.CreateButton(command, text, image, out button, expandimgPath, commandName,
title, content, expandcontent, orientation);
//// 自定义按钮样式
//button.Description = $"测试功能: {text}";
//button.ToolTip = $"执行测试命令: {text}";
}
}
// 程序集注册
//[assembly: ExtensionApplication(typeof(TestAppStart))]
///
/// 测试功能的AppStart实现
///
public class TestAppStart : AppStartBase
{
///
/// 加载UI界面
///
protected override void LoadUI()
{
_ribbonBuilder = CreateRibbonBuilder();
if (_ribbonBuilder != null)
{
bool result = _ribbonBuilder.CreateRibbon();
if (result)
{
"测试功能Ribbon界面加载完成".CadMessage2();
}
else
{
"测试功能Ribbon界面加载失败".CadMessage2();
}
}
}
protected override void LoadDependencies()
{
//不加载任何依赖项
}
///
/// 创建Ribbon构建器
///
protected override RibbonBuilderBase CreateRibbonBuilder()
{
return new TestRibbonBuilder();
}
}
}
_configXmlPath = Path.Combine(ConfigPath._ProfilePath2, "TestConfig.xml");
var imagePath32 = Path.Combine(_iconsBasePath, "icons", $"{image}32.png");
var imagePath16 = Path.Combine(_iconsBasePath, "icons", $"{image}16.png");
```
#### PaletteHelper 停靠面板调用示例
``` CSharp
namespace AutoCAD.EntityTool.Tests
{
///
/// PaletteHelperTest 的摘要说明
///
public class PaletteHelperTest
{
private static PaletteHelper _palette;
[CommandMethod(nameof(ShowPalette))]
public static void ShowPalette()
{
try
{
if (_palette == null)
{
// 创建自定义控件
_palette = new WallSeparationPalette();
_palette.ShowPalette();
}
else
_palette.TogglePalette();
}
catch (System.Exception ex)
{
ex.HandleEntityToolErrorSend(nameof(ShowPalette));
}
}
[CommandMethod(nameof(HidePalette))]
public static void HidePalette()
{
_palette?.HidePalette();
}
}
///
/// 墙体分离专用面板
///
public class WallSeparationPalette : PaletteHelper
{
public WallSeparationPalette() : base("GUO墙体分离", new PaletteView())
{
}
protected override void InitializePalette()
{
base.InitializePalette();
// 自定义设置
this.MinimumSize = new Size(250, 700);
this.Size = new Size(280, 800);
this.Style = PaletteSetStyles.ShowCloseButton | PaletteSetStyles.ShowAutoHideButton;
}
protected override void ApplyAdditionalSettings()
{
base.ApplyAdditionalSettings();
// 墙体分离面板的特殊设置
}
}
///
/// 配置管理面板
///
public class ConfigManagerPalette : PaletteHelper
{
public ConfigManagerPalette() : base("配置管理")
{
}
protected override System.Windows.Controls.UserControl CreateDefaultControl()
{
return new PaletteView(); // 自定义配置管理控件
}
protected override void InitializePalette()
{
base.InitializePalette();
// 配置管理面板的特殊设置
this.MinimumSize = new Size(300, 400);
this.Size = new Size(320, 500);
this.Dock = DockSides.Right;
this.DockEnabled = DockSides.Right;
}
}
}
```
#### jig调用示例
``` CSharp
#region - 测试直线Jig -
///
/// LineJigTest
///
[CommandMethod(nameof(LineJig_Test))]
public void LineJig_Test()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
ed.WriteMessage("\n开始直线Jig测试...");
// 测试方法1:自动添加到模型空间
ed.WriteMessage("\n测试方法1:自动添加到模型空间");
List lineIds = doc.CreateLines(2); // 使用颜色索引2(黄色)
ed.WriteMessage($"\n成功创建 {lineIds.Count} 条直线");
// 测试方法2:使用事务和指定块表记录
ed.WriteMessage("\n\n测试方法2:使用事务和指定块表记录");
using (Transaction trans = db.TransactionManager.StartTransaction())
{
BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
List lineIds2 = doc.CreateLines(trans, btr, 3, "请指定第一个点(事务模式)");
ed.WriteMessage($"\n成功创建 {lineIds2.Count} 条直线(事务模式)");
trans.Commit();
}
ed.WriteMessage("\n\n直线Jig测试完成!");
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("LineJig_Test");
}
}
///
/// 测试撤销功能
///
[CommandMethod(nameof(LineJig_UndoTest))]
public void LineJig_UndoTest()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n测试直线Jig的撤销功能...");
ed.WriteMessage("\n请尝试使用U关键字撤销上一步操作");
List lineIds = doc.CreateLines(4); // 使用颜色索引4(青色)
ed.WriteMessage($"\n最终创建了 {lineIds.Count} 条直线");
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("LineJig_UndoTest");
}
}
///
/// 测试闭合功能
///
[CommandMethod(nameof(LineJig_CloseTest))]
public void LineJig_CloseTest()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n测试直线Jig的闭合功能...");
ed.WriteMessage("\n请创建至少3条线段后使用C关键字闭合");
List lineIds = doc.CreateLines(1); // 使用颜色索引1(红色)
ed.WriteMessage($"\n创建了 {lineIds.Count} 条直线,{(lineIds.Count >= 3 ? "已闭合" : "未闭合")}");
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("LineJig_CloseTest");
}
}
#endregion
#region - 测试圆Jig -
///
/// 圆Jig测试
///
[CommandMethod(nameof(CircleJig_Test))]
public void CircleJig_Test()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n开始圆Jig测试...");
// 测试单个圆创建
ed.WriteMessage("\n测试单个圆创建:");
ObjectId circleId = doc.CreateCircle(3); // 使用颜色索引3(绿色)
if (!circleId.IsNull)
{
ed.WriteMessage("\n单个圆创建成功!");
}
else
{
ed.WriteMessage("\n单个圆创建取消或失败");
}
// 测试事务模式创建
ed.WriteMessage("\n\n测试事务模式创建:");
using (Transaction trans = doc.Database.TransactionManager.StartTransaction())
{
BlockTable bt = trans.GetObject(doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
ObjectId circleId2 = doc.CreateCircle(trans, btr, 5, "请指定圆心点(事务模式)");
if (!circleId2.IsNull)
{
ed.WriteMessage("\n事务模式圆创建成功!");
}
trans.Commit();
}
ed.WriteMessage("\n\n圆Jig测试完成!");
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("CircleJig_Test");
}
}
///
/// 批量创建圆测试
///
[CommandMethod(nameof(CircleJig_MultipleTest))]
public void CircleJig_MultipleTest()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n开始批量创建圆测试...");
List circleIds = doc.CreateMultipleCircles(4, 5); // 创建最多5个青色圆
ed.WriteMessage($"\n成功创建 {circleIds.Count} 个圆");
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("CircleJig_MultipleTest");
}
}
///
/// 直径方式创建圆测试
///
[CommandMethod(nameof(CircleJig_DiameterTest))]
public void CircleJig_DiameterTest()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n开始直径方式创建圆测试...");
ed.WriteMessage("\n创建圆时请输入D关键字选择直径方式");
ObjectId circleId = doc.CreateCircle(2); // 使用颜色索引2(黄色)
if (!circleId.IsNull)
{
ed.WriteMessage("\n直径方式创建圆成功!");
}
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("CircleJig_DiameterTest");
}
}
#endregion
#region - 测试矩形Jig -
///
/// 矩形Jig测试
///
[CommandMethod(nameof(RectangleJig_Test))]
public void RectangleJig_Test()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n开始矩形创建测试...");
// 测试矩形创建
ed.WriteMessage("\n测试矩形创建:");
ObjectId rectangleId = doc.CreateRectangle(3); // 使用颜色索引3(绿色)
if (!rectangleId.IsNull)
{
ed.WriteMessage("\n矩形创建成功!");
}
else
{
ed.WriteMessage("\n矩形创建取消或失败");
}
ed.WriteMessage("\n\n矩形创建测试完成!");
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("RectangleJig_Test");
}
}
///
/// 尺寸方式创建矩形测试
///
[CommandMethod(nameof(RectangleJig_DimensionTest))]
public void RectangleJig_DimensionTest()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n开始尺寸方式创建矩形测试...");
ed.WriteMessage("\n创建矩形时请输入D关键字选择尺寸方式");
ObjectId rectangleId = doc.CreateRectangle(2); // 使用颜色索引2(黄色)
if (!rectangleId.IsNull)
{
ed.WriteMessage("\n尺寸方式创建矩形成功!");
}
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("RectangleJig_DimensionTest");
}
}
///
/// 批量创建矩形测试
///
[CommandMethod(nameof(RectangleJig_MultipleTest))]
public void RectangleJig_MultipleTest()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n开始批量创建矩形测试...");
List rectangleIds = doc.CreateMultipleRectangles(4, 3); // 创建最多3个青色矩形
ed.WriteMessage($"\n成功创建 {rectangleIds.Count} 个矩形");
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("RectangleJig_MultipleTest");
}
}
///
/// 圆角矩形测试
///
[CommandMethod(nameof(RectangleJig_RoundedTest))]
public void RectangleJig_RoundedTest()
{
try
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n开始圆角矩形测试...");
// 获取圆角半径
var radiusOptions = new PromptDistanceOptions("\n指定圆角半径:")
{
DefaultValue = 5.0,
AllowNegative = false
};
var radiusResult = ed.GetDistance(radiusOptions);
if (radiusResult.Status != PromptStatus.OK)
return;
ObjectId roundedRectId = doc.CreateRoundedRectangle(radiusResult.Value, 5); // 使用颜色索引5(蓝色)
if (!roundedRectId.IsNull)
{
ed.WriteMessage("\n圆角矩形创建成功!");
}
}
catch (System.Exception ex)
{
ex.BuildErrorMessage("RectangleJig_RoundedTest");
}
}
#endregion
#region - 测试建筑墙线 -
///
/// 创建单段双线建筑墙线
///
[CommandMethod(nameof(CreateContinuousDoubleWallsTest))]
public static void CreateContinuousDoubleWallsTest()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
try
{
// 获取墙厚参数
PromptDoubleOptions thicknessOptions = new PromptDoubleOptions("\n请输入墙厚 (默认200): ")
{
DefaultValue = 200,
AllowZero = false,
AllowNegative = false
};
PromptDoubleResult thicknessResult = ed.GetDouble(thicknessOptions);
if (thicknessResult.Status != PromptStatus.OK) return;
double wallThickness = thicknessResult.Value;
//var result = doc.CreateSingleDoubleWall(wallThickness);
var result = doc.CreateContinuousDoubleWalls(wallThickness);
ed.WriteMessage($"\n创建了 {result.Count} 条墙线");
}
catch (System.Exception ex)
{
ed.WriteMessage($"\n错误: {ex.Message}");
}
}
///
/// 从现有直线创建双线墙
///
[CommandMethod(nameof(CreateDoubleWallFromLineTest))]
public static void CreateDoubleWallFromLineTest()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
try
{
// 选择直线
PromptEntityOptions entityOptions = new PromptEntityOptions("\n选择要转换为墙线的直线: ");
entityOptions.SetRejectMessage("\n请选择直线对象!");
entityOptions.AddAllowedClass(typeof(Line), false);
PromptEntityResult entityResult = ed.GetEntity(entityOptions);
if (entityResult.Status != PromptStatus.OK) return;
// 获取墙厚参数
PromptDoubleOptions thicknessOptions = new PromptDoubleOptions("\n请输入墙厚 (默认200): ")
{
DefaultValue = 200,
AllowZero = false,
AllowNegative = false
};
PromptDoubleResult thicknessResult = ed.GetDouble(thicknessOptions);
if (thicknessResult.Status != PromptStatus.OK) return;
double wallThickness = thicknessResult.Value;
var result = doc.CreateDoubleWallFromLine(entityResult.ObjectId, wallThickness);
ed.WriteMessage($"\n从直线创建了 {result.Count} 条墙线");
}
catch (System.Exception ex)
{
ed.WriteMessage($"\n错误: {ex.Message}");
}
}
///
/// 测试命令 - 显示所有功能
/// *********
///
[CommandMethod("WALLTEST")]
public static void TestAllWallCommands()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
ed.WriteMessage("\n=== 双线墙工具测试 ===");
ed.WriteMessage("\n可用命令:");
ed.WriteMessage("\nCreateContinuousDoubleWallsTest - 连续绘制双线墙");
ed.WriteMessage("\nCreateDoubleWallFromLineTest - 从直线创建双线墙");
ed.WriteMessage("\nWALLTEST - 显示此帮助");
}
///
/// 添加墙线到数据库
///
private static List AddWallLinesToDatabase(List wallLines, Database database)
{
var objectIds = new List();
if (wallLines == null || wallLines.Count == 0)
return objectIds;
using (var trans = database.TransactionManager.StartTransaction())
{
try
{
var bt = (BlockTable)trans.GetObject(database.BlockTableId, OpenMode.ForRead);
var btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
foreach (var wallLine in wallLines)
{
if (wallLine != null)
{
btr.AppendEntity(wallLine);
trans.AddNewlyCreatedDBObject(wallLine, true);
objectIds.Add(wallLine.ObjectId);
}
}
trans.Commit();
}
catch (System.Exception ex)
{
trans.Abort();
Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"\n数据库错误: {ex.Message}");
}
}
return objectIds;
}
#endregion
```
#### 配置类
``` CSharp
namespace AutoCAD.EntityTools.Config
{
///
/// 配置文件路径工具类
///
public static class ConfigPath
{
///
/// DLL文件路径
///
public static string DllPath { get; set; } = Assembly.GetExecutingAssembly().Location;
///
/// DLL文件所在目录
///
public static string Dllfloder { get; set; } = Path.GetDirectoryName(DllPath);
///
/// 应用程序配置文件路径
///
public static string AppConfig { get; set; } = Path.Combine(Dllfloder, "App.config");
///
/// 图片文件路径
///
public static string ImagePath { get; set; } = Path.Combine(Dllfloder, "image");
///
/// 日志文件路径
///
public static string _LogPath { get; set; } = Path.Combine(Dllfloder, "logs");
///
/// 上层日志文件路径
///
public static string _LogPathUpper { get; set; } = Path.Combine(Path.GetDirectoryName(Dllfloder), "log");
///
/// 图标文件路径
///
public static string IconPath { get; set; } = Path.Combine(Dllfloder, "icons");
///
/// WPF窗口样式文件路径
///
public static string Styles { get; set; } = Path.Combine(Dllfloder, "Styles");
///
/// 配置文件路径
///
public static string ProfilePath { get; set; } = Path.Combine(Dllfloder, "profile");
///
/// 临时图片文件路径
///
public static string ImageTempPath { get; set; } = Path.Combine(Dllfloder, "image/temp");
///
/// 程序集运行根路径
///
public static string AssemblyRunRootPath = Path.GetDirectoryName(typeof(ConfigPath).Assembly.Location);
///
/// 基础文件夹路径
///
public static string BaseFloder { get; set; } = Directory.CreateDirectory(AssemblyRunRootPath).FullName;
///
/// 图标文件路径(上层目录)
///
public static string _IconPath { get; set; } = Path.Combine(Path.GetDirectoryName(Dllfloder), "icons");
///
/// 临时文件路径
///
public static string _TempPath { get; set; } = Path.Combine(Path.GetDirectoryName(Dllfloder), "temp");
///
/// 配置文件路径(上层目录)
///
public static string _ProfilePath { get; set; } = Path.Combine(Path.GetDirectoryName(Dllfloder), "profile");
///
/// 配置文件路径2(程序集运行目录)
///
public static string _ProfilePath2 { get; set; } = Path.Combine(AssemblyRunRootPath, "profile");
}
}
```
#### RegistryManage 注册表封装类调用示例
``` CSharp
namespace AutoCAD.EntityTools.ConsoleTests
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("测试 ...");
#region 注册表注册测试
// 创建注册服务实例
var registrationService = new AddinRegistrationService();
// 注册插件
bool success = registrationService.RegisterAddin(
addinName: "AutoCAD.EntityTool.Tests测试",
description: "用于提高工作效率...",
filePath: @"D:\Desk\GUO项目文件夹\AutoCADEntityTool\auto-cad.-entity-tools\AutoCAD.EntityTool\AutoCAD.EntityTool.Tests\bin\Debug\AutoCAD.EntityTools.dll"
);
// 显示结果
if (success)
{
Console.WriteLine("注册安装完成,按任意键退出...");
Console.WriteLine("注册完成"); // 假设这是扩展方法
}
else
{
Console.WriteLine("部分或全部安装失败,按任意键退出...");
}
#endregion
Console.ReadKey();
}
}
}
Versions.txt
R15.0,AutoCAD 2002
R16.0,AutoCAD 2004
R16.1,AutoCAD 2005
R16.2,AutoCAD 2006
R17.0,AutoCAD 2007
R17.1,AutoCAD 2008
R17.2,AutoCAD 2009
R18.0,AutoCAD 2010
R18.1,AutoCAD 2011
R18.2,AutoCAD 2012
R19.0,AutoCAD 2013
R19.1,AutoCAD 2014
R20.0,AutoCAD 2015
R20.1,AutoCAD 2016
R21.0,AutoCAD 2017
R22.0,AutoCAD 2018
R23.0,AutoCAD 2019
R23.1,AutoCAD 2020
R24.0,AutoCAD 2021
R24.1,AutoCAD 2022
R24.2,AutoCAD 2023
R24.3,AutoCAD 2024
```
#### DwgToDxfConverter 转换器
``` CSharp
namespace AutoCAD.EntityTools.Convert
{
///
/// DWG到DXF转换器
///
public class DwgToDxfConverter
{
///
/// 将DWG文件转换为DXF格式
///
/// 源DWG文件路径
/// 目标DXF文件路径
/// DXF版本
/// 转换是否成功
public static bool ConvertDwgToDxf(string sourceDwgPath, string targetDxfPath, string dxfVersion = "AC1027")
///
/// 等待文件释放
///
/// 文件路径
/// 超时时间(毫秒)
/// 重试间隔(毫秒)
/// 文件是否可用
private static bool WaitForFileRelease(string filePath, int timeoutMs, int retryIntervalMs = 100)
///
/// 批量转换DWG文件为DXF格式
///
/// 源目录
/// 目标目录
/// 搜索模式
/// DXF版本
/// 成功转换的文件数量
public static int BatchConvertDwgToDxf(string sourceDirectory, string targetDirectory, string searchPattern = "*.dwg", string dxfVersion = "AC1027")
///
/// 使用COM接口进行转换(备用方案)
///
/// 源DWG文件路径
/// 目标DXF文件路径
/// 转换是否成功
public static bool ConvertUsingComInterface(string sourceDwgPath, string targetDxfPath)
}
///
/// DWG/DXF双向转换器
///
public class DwgDxfConverter
{
///
/// 将DWG文件转换为DXF格式
///
/// 源DWG文件路径
/// 目标DXF文件路径
/// DXF版本
/// 转换是否成功
public static bool ConvertDwgToDxf(string sourceDwgPath, string targetDxfPath, string dxfVersion = "AC1027")
///
/// 将DXF文件转换为DWG格式
///
/// 源DXF文件路径
/// 目标DWG文件路径
/// DWG版本
/// 转换是否成功
public static bool ConvertDxfToDwg(string sourceDxfPath, string targetDwgPath, string dwgVersion = "AC1027")
///
/// 使用COM接口进行DXF到DWG转换
///
/// 源DXF文件路径
/// 目标DWG文件路径
/// 转换是否成功
public static bool ConvertDxfToDwgUsingComInterface(string sourceDxfPath, string targetDwgPath)
///
/// 转换失败时的备用方案:直接修改文件扩展名
///
/// 源文件路径
/// 目标文件路径
/// 源文件扩展名
/// 目标文件扩展名
/// 转换是否成功
private static bool TryRenameExtensionAsFallback(string sourcePath, string targetPath, string sourceExt, string targetExt)
///
/// 批量转换DXF文件为DWG格式
///
/// 源目录
/// 目标目录
/// 搜索模式
/// DWG版本
/// 成功转换的文件数量
public static int BatchConvertDxfToDwg(string sourceDirectory, string targetDirectory, string searchPattern = "*.dxf", string dwgVersion = "AC1027")
///
/// 等待文件释放
///
/// 文件路径
/// 超时时间(毫秒)
/// 重试间隔(毫秒)
/// 文件是否可用
private static bool WaitForFileRelease(string filePath, int timeoutMs, int retryIntervalMs = 100)
///
/// 批量转换DWG文件为DXF格式
///
/// 源目录
/// 目标目录
/// 搜索模式
/// DXF版本
/// 成功转换的文件数量
public static int BatchConvertDwgToDxf(string sourceDirectory, string targetDirectory, string searchPattern = "*.dwg", string dxfVersion = "AC1027")
}
}
```
##### AutoCAD颜色索引列表_index:
# AutoCAD 颜色索引表
## 标准颜色索引 (1-255)
| 索引 | 颜色名称 | RGB值 | 预览 | 说明 |
|------|----------|-------|------|------|
| 1 | 红色 | (255, 0, 0) | 🔴 | 标准红色 |
| 2 | 黄色 | (255, 255, 0) | 🟡 | 标准黄色 |
| 3 | 绿色 | (0, 255, 0) | 🟢 | 标准绿色 |
| 4 | 青色 | (0, 255, 255) | 🔵 | 青色/天蓝色 |
| 5 | 蓝色 | (0, 0, 255) | 🔵 | 标准蓝色 |
| 6 | 洋红色 | (255, 0, 255) | 🟣 | 洋红色/粉紫色 |
| 7 | 白色/黑色 | (255, 255, 255) | ⚪ | 白色(在黑色背景上) |
| 8 | 深灰色 | (128, 128, 128) | ◼️ | 深灰色 |
| 9 | 浅灰色 | (192, 192, 192) | ◻️ | 浅灰色 |
## 特殊颜色索引
| 索引 | 颜色名称 | 说明 |
|------|----------|------|
| 0 | ByBlock | 随块颜色 |
| 256 | ByLayer | 随层颜色 |
| 257 | ByColor | 按颜色 |
| 258 | ByMaterial | 按材质 |
## 完整的1-255颜色索引表
### 1-15: 基本颜色
| 索引 | RGB | 颜色名称 | 索引 | RGB | 颜色名称 |
|------|-----|----------|------|-----|----------|
| 1 | (255, 0, 0) | 红色 | 9 | (255, 127, 0) | 橙色 |
| 2 | (255, 255, 0) | 黄色 | 10 | (255, 127, 127) | 浅粉红 |
| 3 | (0, 255, 0) | 绿色 | 11 | (165, 0, 0) | 深红色 |
| 4 | (0, 255, 255) | 青色 | 12 | (165, 82, 82) | 棕色 |
| 5 | (0, 0, 255) | 蓝色 | 13 | (165, 165, 0) | 深黄色 |
| 6 | (255, 0, 255) | 洋红色 | 14 | (0, 165, 0) | 深绿色 |
| 7 | (255, 255, 255) | 白色 | 15 | (0, 165, 165) | 深青色 |
| 8 | (128, 128, 128) | 灰色 | | | |
### 16-31: 标准颜色扩展
| 索引 | RGB | 颜色名称 |
|------|-----|----------|
| 16 | (0, 0, 165) | 深蓝色 |
| 17 | (165, 0, 165) | 深洋红 |
| 18 | (165, 165, 165) | 浅灰色 |
| 19 | (76, 76, 76) | 深灰色 |
| 20 | (114, 114, 114) | 中灰色 |
| 21 | (191, 191, 191) | 亮灰色 |
| 22 | (255, 0, 127) | 粉红色 |
| 23 | (255, 127, 255) | 浅洋红 |
| 24 | (127, 0, 255) | 紫色 |
| 25 | (127, 127, 255) | 淡紫色 |
| 26 | (0, 127, 255) | 天蓝色 |
| 27 | (0, 255, 127) | 春绿色 |
| 28 | (127, 255, 0) | 黄绿色 |
| 29 | (255, 127, 0) | 橙黄色 |
| 30 | (255, 0, 0) | 红色 |
| 31 | (255, 63, 0) | 红橙色 |
### 常用工程颜色 (32-63)
| 索引 | RGB | 颜色名称 | 用途 |
|------|-----|----------|------|
| 32 | (255, 127, 63) | 橙红色 | 警告色 |
| 33 | (255, 191, 127) | 浅橙色 | |
| 34 | (255, 223, 127) | 浅黄色 | |
| 35 | (255, 255, 191) | 淡黄色 | 高亮 |
| 36 | (223, 255, 127) | 黄绿色 | |
| 37 | (191, 255, 127) | 浅绿色 | |
| 38 | (127, 255, 127) | 鲜绿色 | 通过/成功 |
| 39 | (127, 255, 191) | 海绿色 | |
| 40 | (127, 255, 223) | 淡青色 | |
| 41 | (127, 223, 255) | 天蓝色 | 信息 |
| 42 | (127, 191, 255) | 淡蓝色 | |
| 43 | (127, 127, 255) | 薰衣草色 | |
| 44 | (191, 127, 255) | 淡紫色 | |
| 45 | (223, 127, 255) | 淡洋红 | |
| 46 | (255, 127, 223) | 粉红色 | |
| 47 | (255, 127, 191) | 热粉色 | |
## C# 代码中的颜色常量
```csharp
///
/// AutoCAD 颜色索引常量
///
public static class AcadColors
{
// 特殊颜色
public const short ByBlock = 0;
public const short ByLayer = 256;
public const short ByColor = 257;
public const short ByMaterial = 258;
// 标准颜色
public const short Red = 1;
public const short Yellow = 2;
public const short Green = 3;
public const short Cyan = 4;
public const short Blue = 5;
public const short Magenta = 6;
public const short White = 7;
public const short Gray = 8;
public const short LightGray = 9;
// 常用工程颜色
public const short Orange = 30;
public const short DarkRed = 11;
public const short Brown = 12;
public const short DarkYellow = 13;
public const short DarkGreen = 14;
public const short DarkCyan = 15;
public const short DarkBlue = 16;
public const short DarkMagenta = 17;
// 获取颜色名称的辅助方法
public static string GetColorName(short colorIndex)
{
return colorIndex switch
{
0 => "ByBlock",
1 => "Red",
2 => "Yellow",
3 => "Green",
4 => "Cyan",
5 => "Blue",
6 => "Magenta",
7 => "White",
8 => "Gray",
9 => "LightGray",
11 => "DarkRed",
12 => "Brown",
13 => "DarkYellow",
14 => "DarkGreen",
15 => "DarkCyan",
16 => "DarkBlue",
17 => "DarkMagenta",
30 => "Orange",
256 => "ByLayer",
257 => "ByColor",
258 => "ByMaterial",
_ => $"Color{colorIndex}"
};
}
// 创建颜色对象
public static Color FromIndex(short colorIndex)
{
return Color.FromColorIndex(ColorMethod.ByAci, colorIndex);
}
}
```
## 使用示例
```csharp
// 使用颜色索引
entity.ColorIndex = AcadColors.Red; // 红色
entity.ColorIndex = AcadColors.Green; // 绿色
entity.ColorIndex = AcadColors.ByLayer; // 随层
// 使用颜色对象
entity.Color = AcadColors.FromIndex(AcadColors.Blue);
// 获取颜色名称
string colorName = AcadColors.GetColorName(entity.ColorIndex);
```
| .. | ... |
## QQ交流群 : 891788576