NetCad 2.3.1

dotnet add package NetCad --version 2.3.1
                    
NuGet\Install-Package NetCad -Version 2.3.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NetCad" Version="2.3.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NetCad" Version="2.3.1" />
                    
Directory.Packages.props
<PackageReference Include="NetCad" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NetCad --version 2.3.1
                    
#r "nuget: NetCad, 2.3.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NetCad@2.3.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NetCad&version=2.3.1
                    
Install as a Cake Addin
#tool nuget:?package=NetCad&version=2.3.1
                    
Install as a Cake Tool

NetCad - AutoCAD二次开发封装库

.NET Framework AutoCAD License Version Build Status Code Quality

📖 项目简介

NetCad 是一个专为AutoCAD二次开发设计的.NET封装库,旨在简化AutoCAD API的使用,提高开发效率。该库提供了丰富的工具类和方法,让开发者能够更快速、更简洁地开发AutoCAD插件。

✨ 主要特性

  • 🚀 简化API调用 - 封装复杂的AutoCAD API,提供简洁易用的接口
  • 🎯 功能全面 - 覆盖实体绘制、数据库操作、用户交互等核心功能
  • 🔧 扩展性强 - 模块化设计,支持自定义扩展
  • 🛡️ 线程安全 - 提供线程安全的文档操作机制
  • 📊 数据管理 - 灵活的数据存储和扩展数据支持
  • 🎨 交互友好 - 丰富的用户交互和动态操作功能
  • 性能优化 - 高效的算法实现和内存管理
  • 🎛️ 界面集成 - 支持Ribbon界面定制

🏗️ 架构特点

  • 模块化设计 - 清晰的模块划分,便于维护和扩展
  • 扩展方法 - 大量使用C#扩展方法,提供流畅的API
  • 工厂模式 - 实体创建采用工厂模式,简化对象创建
  • 事务安全 - 所有数据库操作都支持事务处理
  • 错误处理 - 完善的异常处理机制

👨‍💻 作者信息

🎯 支持版本

  • AutoCAD: 2013 - 2023
  • .NET Framework: 4.8
  • 开发语言: C#
  • 开发环境: Visual Studio 2017+

📦 安装说明

环境要求

  1. Visual Studio 2017 或更高版本
  2. .NET Framework 4.8
  3. AutoCAD 2013-2023 任一版本
  4. Windows 7/8/10/11

安装步骤

  1. 克隆项目

    git clone https://github.com/zhangfuwang666/NetCad.git
    
  2. 打开解决方案

    cd NetCad
    start NetCad.sln
    
  3. 还原NuGet包

    • 在Visual Studio中右键解决方案
    • 选择"还原NuGet包"
  4. 编译项目

    • 选择Release配置
    • 生成解决方案

NuGet包依赖

<PackageReference Include="AutoCAD.NET" Version="23.1.0" />
<PackageReference Include="NPOI" Version="2.3.0" />

🚀 快速开始

基本使用示例

using NetCad;
using Autodesk.AutoCAD.Geometry;

// 绘制一条直线
Point3d startPoint = new Point3d(0, 0, 0);
Point3d endPoint = new Point3d(100, 100, 0);
ObjectId lineId = Draw.Line(startPoint, endPoint);

// 获取用户输入
string userInput = Interaction.GetString("请输入文字: ");

// 创建图层
ObjectId layerId = DbHelper.GetLayerId("新图层");

// 线程安全操作
App.LockAndExecute(() => {
    // 在这里进行AutoCAD操作
    Draw.Circle(new Point3d(50, 50, 0), 25);
});

实体绘制示例

// 绘制圆
ObjectId circleId = Draw.Circle(new Point3d(0, 0, 0), 50);

// 绘制多段线
Point3d[] points = {
    new Point3d(0, 0, 0),
    new Point3d(100, 0, 0),
    new Point3d(100, 100, 0),
    new Point3d(0, 100, 0)
};
ObjectId polylineId = Draw.Polyline(points);

// 插入块
ObjectId blockId = Draw.Insert("块名称", new Point3d(0, 0, 0));

📚 API文档

🔧 应用程序管理 (App)

应用程序级别的管理功能,包括文档操作、版本检测等。

文档操作
// 获取当前文件夹路径
string currentFolder = App.CurrentFolder;

// 获取文档文件夹路径
string docFolder = App.DocumentFolder;

// 检查文档是否已保存
bool isSaved = App.IsDocumentSaved();

// 获取所有打开的文档
List<Document> docs = App.GetAllOpenedDocuments();

// 线程安全执行
App.LockAndExecute(() => {
    // 安全操作代码
});

// 打开文档
Document doc = App.OpenDocument("C:\\path\\to\\file.dwg");
版本检测
// 获取AutoCAD版本
string version = App.GetAcadRVersion();

// 获取年份版本
string year = App.GetAcadYearVersion();

🗄️ 数据库操作 (DbHelper)

提供符号表操作、组管理、扩展数据存储等功能。

图层操作
// 获取图层ID
ObjectId layerId = DbHelper.GetLayerId("图层名");

// 获取所有图层名称
string[] layerNames = DbHelper.GetAllLayerNames();

// 确保图层开启
DbHelper.EnsureLayerOn("图层名");
块操作
// 获取块ID
ObjectId blockId = DbHelper.GetBlockId("块名");

// 获取所有块名称
string[] blockNames = DbHelper.GetAllBlockNames();

// 获取块属性
BlockReference blockRef = blockId.QOpenForRead<BlockReference>();
Dictionary<string, string> attrs = blockRef.GetBlockAttributes();
扩展数据操作
// 使用新的FlexDataStore(推荐)
var dataStore = new FlexDataStore(dictionaryId);
dataStore.SetValue("key", "value");
string value = dataStore.GetValue("key");

// 传统XData操作(已废弃)
entity.SetCode("代码值");
string code = entity.GetCode();

💬 用户交互 (Interaction)

提供命令行交互、实体选择、视图操作等功能。

用户输入
// 获取字符串
string input = Interaction.GetString("请输入文字: ");

// 获取数值
double value = Interaction.GetValue("请输入数值: ");

// 获取点
Point3d point = Interaction.GetPoint("请选择点: ");

// 获取关键字
string[] keywords = { "选项1", "选项2", "选项3" };
string choice = Interaction.GetKeywords("请选择: ", keywords);
实体选择
// 选择单个实体
ObjectId entityId = Interaction.GetEntity("请选择实体: ");

// 选择多个实体
ObjectId[] entities = Interaction.GetSelection("请选择多个实体: ");

// 窗口选择
ObjectId[] windowEntities = Interaction.GetWindowSelection(
    new Point3d(0, 0, 0), 
    new Point3d(100, 100, 0)
);
视图操作
// 高亮对象
Interaction.HighlightObjects(entityIds);

// 缩放对象
Interaction.ZoomObjects(entityIds);

// 取消高亮
Interaction.UnhighlightObjects(entityIds);

🎨 实体绘制 (Draw)

提供各种几何实体的绘制功能,自动添加到当前空间。

基本几何体
// 绘制直线
ObjectId lineId = Draw.Line(point1, point2);

// 绘制圆
ObjectId circleId = Draw.Circle(center, radius);

// 绘制圆弧
ObjectId arcId = Draw.Arc3P(point1, point2, point3);

// 绘制多段线
ObjectId polylineId = Draw.Polyline(points);

// 绘制矩形
ObjectId rectId = Draw.Rectang(minPoint, maxPoint);
复杂几何体
// 绘制椭圆
ObjectId ellipseId = Draw.Ellipse(center, endX, radiusY);

// 绘制样条曲线
ObjectId splineId = Draw.SplineFit(points);

// 绘制填充
ObjectId hatchId = Draw.Hatch("SOLID", seedPoint);

// 绘制表格
ObjectId tableId = Draw.Table(position, title, contents, rowHeight, columnWidth, textHeight);
块操作
// 插入块
ObjectId blockId = Draw.Insert("块名", position);

// 创建块
ObjectId newBlockId = Draw.Block(entityIds, "新块名");

// 从外部文件插入块
ObjectId externalBlockId = Draw.BlockInDwg("块名", "外部文件.dwg");

🔧 实体创建 (NoDraw)

创建实体但不添加到空间,用于复杂几何体构建。

// 创建直线(不添加到空间)
Line line = NoDraw.Line(point1, point2);

// 创建圆(不添加到空间)
Circle circle = NoDraw.Circle(center, radius);

// 创建多段线(不添加到空间)
Polyline polyline = NoDraw.Polyline(points);

// 手动添加到空间
ObjectId entityId = line.AddToCurrentSpace();

🎯 动态交互 (Jig)

提供动态交互功能,支持实时预览和操作。

// 动态插入实体
ObjectId entityId = Interaction.InsertEntity(entity, "指定插入点");

// 动态缩放插入
ObjectId scaledEntityId = Interaction.InsertScalingEntity(entity, basePoint, "指定对角点");

// 动态旋转插入
ObjectId rotatedEntityId = Interaction.InsertRotationEntity(entity, center, "指定方向");

📊 数据存储 (FlexDataStore)

灵活的数据存储系统,支持任意键值对。

// 创建数据存储
var dataStore = new FlexDataStore(dictionaryId);

// 存储数据
dataStore.SetValue("name", "张三")
         .SetValue("age", "25")
         .SetValue("department", "工程部");

// 读取数据
string name = dataStore.GetValue("name");
string age = dataStore.GetValue("age");

🧮 算法工具 (Algorithms)

提供丰富的几何算法和数学计算功能。

曲线操作
// 获取点到曲线的距离
double distance = curve.GetDistToPoint(point);

// 获取曲线上的点
Point3d pointOnCurve = curve.GetPointAtDist(distance);

// 获取子曲线
Curve subCurve = curve.GetSubCurve(new Interv(start, end));

// 获取曲线上的点集合
IEnumerable<Point3d> points = curve.GetPoints(1.0); // 参数间隔1.0
几何计算
// 获取包围盒
Extents3d extents = entityIds.GetExtents();

// 获取中心点
Point3d center = extents.GetCenter();

// 扩展包围盒
Extents3d expanded = extents.Expand(1.5); // 扩展1.5倍

// 判断点是否在包围盒内
bool isInside = extents.IsPointIn(point);
多段线操作
// 判断是否自相交
bool isSelfIntersecting = polyline.IsSelfIntersecting();

// 获取质心
Point3d centroid = polyline.Centroid();

// 判断点是否在多段线内
bool isInside = polyline.IsPointIn(point);

// 连接多段线
Polyline joined = polyline1.PolyJoin(polyline2);
向量计算
// 计算角度
double angle = vector1.ZeroToPiAngleTo(vector2);

// 计算叉积
double cross = vector1.Kross(vector2);

// 向量转换
Vector3d vector3d = vector2d.ToVector3d();

🔄 实体修改 (Modify)

提供实体变换和编辑功能。

基本变换
// 移动实体
entityId.Move(new Vector3d(10, 10, 0));

// 旋转实体
entityId.Rotate(center, Math.PI / 2); // 旋转90度

// 缩放实体
entityId.Scale(basePoint, 2.0); // 放大2倍

// 镜像实体
ObjectId mirroredId = entityId.Mirror(mirrorLine, true); // 复制镜像
高级操作
// 偏移曲线
ObjectId offsetId = curveId.Offset(distance, sidePoint);

// 打断曲线
ObjectId[] brokenIds = curveId.Break(point1, point2);

// 炸开实体
ObjectId[] explodedIds = entityId.Explode();

// 删除实体
entityId.Erase();
组操作
// 创建组
ObjectId groupId = entityIds.AddGroup("组名");

// 添加到组
Modify.AppendToGroup(groupId, entityId1, entityId2);

// 解组
Modify.Ungroup(groupId);

// 设置图层
entityId.SetLayer("图层名");

// 设置线型
entityId.SetLinetype("线型名", 1.0);

🛠️ 辅助工具 (Helper)

提供各种辅助功能。

文件操作
// 保存文件对话框
string savePath = Interaction.SaveFileDialogBySystem("保存文件", "默认文件名", "DWG文件|*.dwg");

// 打开文件对话框
string openPath = Interaction.OpenFileDialogBySystem("打开文件", "", "DWG文件|*.dwg");

// 选择文件夹
string folderPath = Interaction.FolderDialog("选择文件夹");
Excel操作 (NpoiHelper)
// 读取Excel文件
var workbook = NpoiHelper.ReadExcel("文件路径.xlsx");

// 写入Excel文件
NpoiHelper.WriteExcel("文件路径.xlsx", data);

// 读取特定工作表
var sheet = NpoiHelper.GetSheet(workbook, "Sheet1");

// 读取单元格数据
string cellValue = NpoiHelper.GetCellValue(sheet, 0, 0);
字符串处理 (StringHelper)
// 字符串扩展方法
string result = StringHelper.SomeMethod(input);
系统信息 (SystemHelper)
// 获取系统信息
var systemInfo = SystemHelper.GetSystemInfo();

🎛️ Ribbon界面 (Ribbon)

支持自定义Ribbon界面。

基本使用
// 加载Ribbon菜单
RibbonMenuLoader.LoadRibbonMenu("RibbonMenu.xml");

// 处理命令
[CommandMethod("MyCommand")]
public void MyCommand()
{
    // 命令实现
}
XML配置示例
<Ribbon>
  <Tabs>
    <Tab Title="我的工具">
      <Panels>
        <Panel Title="绘图工具">
          <Buttons>
            <Button Text="绘制圆" Command="DrawCircle" Icon="circle.png" />
            <Button Text="绘制矩形" Command="DrawRectangle" Icon="rect.png" />
          </Buttons>
        </Panel>
      </Panels>
    </Tab>
  </Tabs>
</Ribbon>

📝 日志管理

// 写入日志
LogManager.Write("操作信息");

// 创建日志表
var logTable = new LogTable(20, 30, 40);
string row = logTable.GetRow("列1", "列2", "列3");

🔧 工具类 (Utils)

提供通用工具方法。

// 获取相对路径
string relativePath = Utils.GetRelativePath(basePath, fullPath);

// 解析INI文件
Dictionary<string, Dictionary<string, string>> iniData = new Dictionary<string, Dictionary<string, string>>();
bool success = Utils.ParseIniFile("config.ini", iniData);

🚀 性能优化

最佳实践

  1. 使用事务管理

    using (Transaction trans = db.TransactionManager.StartTransaction())
    {
        // 数据库操作
        trans.Commit();
    }
    
  2. 批量操作

    // 批量绘制
    ObjectId[] entityIds = Draw.Line(points);
    
    // 批量修改
    entityIds.ForEach(id => id.SetLayer("图层名"));
    
  3. 内存管理

    // 及时释放资源
    using (var entity = entityId.QOpenForRead<Entity>())
    {
        // 使用实体
    }
    
  4. 避免频繁的数据库访问

    // 缓存常用数据
    var layerIds = DbHelper.GetAllLayerIds();
    

性能监控

// 使用日志记录性能
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
// 执行操作
stopwatch.Stop();
LogManager.Write($"操作耗时: {stopwatch.ElapsedMilliseconds}ms");

🔧 扩展开发

自定义扩展方法

public static class MyExtensions
{
    public static void MyCustomMethod(this Entity entity)
    {
        // 自定义逻辑
    }
    
    public static ObjectId MyCustomDraw(this Point3d point)
    {
        // 自定义绘制逻辑
        return Draw.Circle(point, 10);
    }
}

自定义Jig

public class MyCustomJig : DrawJig
{
    private Entity _entity;
    private Point3d _position;
    
    public MyCustomJig(Entity entity) : base()
    {
        _entity = entity;
    }
    
    protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw)
    {
        // 绘制逻辑
        return true;
    }
    
    protected override SamplerStatus Sampler(JigPrompts prompts)
    {
        // 采样逻辑
        return SamplerStatus.OK;
    }
}

自定义命令

[CommandMethod("MyCustomCommand")]
public void MyCustomCommand()
{
    try
    {
        // 命令实现
        Interaction.WriteLine("命令执行成功");
    }
    catch (Exception ex)
    {
        Interaction.WriteLine($"错误: {ex.Message}");
    }
}

📋 开发规范

代码风格

  1. 命名规范

    • 类名:PascalCase
    • 方法名:PascalCase
    • 变量名:camelCase
    • 常量:UPPER_CASE
  2. 注释规范

    /// <summary>
    /// 方法功能描述
    /// </summary>
    /// <param name="param">参数说明</param>
    /// <returns>返回值说明</returns>
    public static ObjectId MyMethod(Point3d param)
    {
        // 实现代码
    }
    
  3. 异常处理

    try
    {
        // 可能出错的代码
    }
    catch (System.Exception ex)
    {
        Interaction.WriteLine($"错误: {ex.Message}");
        LogManager.Write($"异常: {ex}");
    }
    

项目结构

NetCad/
├── Core/           # 核心功能
├── Extension/      # 扩展方法
├── Geometry/       # 几何计算
├── Helper/         # 辅助工具
├── Jig/           # 动态交互
├── Ribbon/        # 界面定制
└── Utils/         # 工具类

🐛 常见问题

Q: 如何处理线程安全问题?

A: 使用 App.LockAndExecute() 方法进行线程安全操作:

App.LockAndExecute(() => {
    // 在这里进行AutoCAD操作
});

Q: 如何获取实体的扩展数据?

A: 推荐使用新的 FlexDataStore 类:

var dataStore = new FlexDataStore(dictionaryId);
dataStore.SetValue("key", "value");

Q: 如何动态插入实体?

A: 使用 Interaction.InsertEntity() 方法:

ObjectId entityId = Interaction.InsertEntity(entity, "指定插入点");

Q: 如何处理大量实体的性能问题?

A: 使用批量操作和事务管理:

App.LockAndExecute(() => {
    using (Transaction trans = db.TransactionManager.StartTransaction())
    {
        // 批量操作
        foreach (var entity in entities)
        {
            // 处理实体
        }
        trans.Commit();
    }
});

Q: 如何自定义Ribbon界面?

A: 修改 RibbonMenu.xml 文件并实现对应的命令方法。

📚 学习资源

官方文档

示例项目

社区资源

🤝 贡献指南

欢迎提交 Issue 和 Pull Request 来改进这个项目。

贡献流程

  1. Fork 本项目
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request

贡献规范

  1. 代码质量

    • 遵循现有代码风格
    • 添加适当的注释
    • 确保代码通过编译
  2. 测试要求

    • 添加单元测试
    • 确保功能正常工作
    • 测试不同AutoCAD版本
  3. 文档更新

    • 更新README文档
    • 添加API文档
    • 提供使用示例

📄 许可证

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

📞 联系方式

🙏 致谢

感谢所有为这个项目做出贡献的开发者!


⭐ 如果这个项目对您有帮助,请给它一个星标!


注意: 本项目仅供学习和研究使用,请遵守相关法律法规和AutoCAD使用协议。

Product Compatible and additional computed target framework versions.
.NET Framework net48 is compatible.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETFramework 4.8

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.3.1 116 7/18/2025
2.3.0.1 156 12/7/2024
2.3.0 119 12/7/2024
2.2.0.3 201 4/17/2024
2.2.0.2 148 3/27/2024
2.2.0.1 135 3/27/2024
2.2.0 137 3/22/2024
2.1.0 162 2/29/2024
2.0.12 114 2/29/2024
2.0.11 207 12/22/2023
2.0.10 149 12/22/2023
2.0.0.9 185 12/6/2023
2.0.0.8 139 12/6/2023
2.0.0.7 153 12/3/2023
2.0.0.6 142 12/3/2023
2.0.0.5 145 12/2/2023
2.0.0.4 158 12/1/2023
2.0.0.3 158 11/16/2023
2.0.0.2 131 11/16/2023
2.0.0.1 138 11/15/2023
2.0.0 132 11/15/2023
1.0.0.4 140 11/14/2023
1.0.0.3 642 1/20/2022
1.0.0.2 509 1/20/2022
1.0.0.1 503 1/20/2022

更新图标.