# Netcad
**Repository Path**: zmlr007/Netcad
## Basic Information
- **Project Name**: Netcad
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2025-11-21
- **Last Updated**: 2025-11-21
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# NetCad - AutoCAD二次开发封装库
[](https://dotnet.microsoft.com/download/dotnet-framework/net48)
[](https://www.autodesk.com/products/autocad)
[](LICENSE)
[](NetCad/Properties/AssemblyInfo.cs)
[](https://github.com/zhangfuwang666/NetCad)
[](https://github.com/zhangfuwang666/NetCad)
## 📖 项目简介
NetCad 是一个专为AutoCAD二次开发设计的.NET封装库,旨在简化AutoCAD API的使用,提高开发效率。该库提供了丰富的工具类和方法,让开发者能够更快速、更简洁地开发AutoCAD插件。
### ✨ 主要特性
- 🚀 **简化API调用** - 封装复杂的AutoCAD API,提供简洁易用的接口
- 🎯 **功能全面** - 覆盖实体绘制、数据库操作、用户交互等核心功能
- 🔧 **扩展性强** - 模块化设计,支持自定义扩展
- 🛡️ **线程安全** - 提供线程安全的文档操作机制
- 📊 **数据管理** - 灵活的数据存储和扩展数据支持
- 🎨 **交互友好** - 丰富的用户交互和动态操作功能
- ⚡ **性能优化** - 高效的算法实现和内存管理
- 🎛️ **界面集成** - 支持Ribbon界面定制
### 🏗️ 架构特点
- **模块化设计** - 清晰的模块划分,便于维护和扩展
- **扩展方法** - 大量使用C#扩展方法,提供流畅的API
- **工厂模式** - 实体创建采用工厂模式,简化对象创建
- **事务安全** - 所有数据库操作都支持事务处理
- **错误处理** - 完善的异常处理机制
## 👨💻 作者信息
- **作者**: ZhangFuWang
- **邮箱**: fuwang.zhang@qq.com
- **GitHub**: [zhangfuwang666/NetCad](https://github.com/zhangfuwang666/NetCad)
- **许可证**: MIT License
## 🎯 支持版本
- **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. **克隆项目**
```bash
git clone https://github.com/zhangfuwang666/NetCad.git
```
2. **打开解决方案**
```bash
cd NetCad
start NetCad.sln
```
3. **还原NuGet包**
- 在Visual Studio中右键解决方案
- 选择"还原NuGet包"
4. **编译项目**
- 选择Release配置
- 生成解决方案
### NuGet包依赖
```xml
```
## 🚀 快速开始
### 基本使用示例
```csharp
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);
});
```
### 实体绘制示例
```csharp
// 绘制圆
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)
应用程序级别的管理功能,包括文档操作、版本检测等。
#### 文档操作
```csharp
// 获取当前文件夹路径
string currentFolder = App.CurrentFolder;
// 获取文档文件夹路径
string docFolder = App.DocumentFolder;
// 检查文档是否已保存
bool isSaved = App.IsDocumentSaved();
// 获取所有打开的文档
List docs = App.GetAllOpenedDocuments();
// 线程安全执行
App.LockAndExecute(() => {
// 安全操作代码
});
// 打开文档
Document doc = App.OpenDocument("C:\\path\\to\\file.dwg");
```
#### 版本检测
```csharp
// 获取AutoCAD版本
string version = App.GetAcadRVersion();
// 获取年份版本
string year = App.GetAcadYearVersion();
```
### 🗄️ 数据库操作 (DbHelper)
提供符号表操作、组管理、扩展数据存储等功能。
#### 图层操作
```csharp
// 获取图层ID
ObjectId layerId = DbHelper.GetLayerId("图层名");
// 获取所有图层名称
string[] layerNames = DbHelper.GetAllLayerNames();
// 确保图层开启
DbHelper.EnsureLayerOn("图层名");
```
#### 块操作
```csharp
// 获取块ID
ObjectId blockId = DbHelper.GetBlockId("块名");
// 获取所有块名称
string[] blockNames = DbHelper.GetAllBlockNames();
// 获取块属性
BlockReference blockRef = blockId.QOpenForRead();
Dictionary attrs = blockRef.GetBlockAttributes();
```
#### 扩展数据操作
```csharp
// 使用新的FlexDataStore(推荐)
var dataStore = new FlexDataStore(dictionaryId);
dataStore.SetValue("key", "value");
string value = dataStore.GetValue("key");
// 传统XData操作(已废弃)
entity.SetCode("代码值");
string code = entity.GetCode();
```
### 💬 用户交互 (Interaction)
提供命令行交互、实体选择、视图操作等功能。
#### 用户输入
```csharp
// 获取字符串
string input = Interaction.GetString("请输入文字: ");
// 获取数值
double value = Interaction.GetValue("请输入数值: ");
// 获取点
Point3d point = Interaction.GetPoint("请选择点: ");
// 获取关键字
string[] keywords = { "选项1", "选项2", "选项3" };
string choice = Interaction.GetKeywords("请选择: ", keywords);
```
#### 实体选择
```csharp
// 选择单个实体
ObjectId entityId = Interaction.GetEntity("请选择实体: ");
// 选择多个实体
ObjectId[] entities = Interaction.GetSelection("请选择多个实体: ");
// 窗口选择
ObjectId[] windowEntities = Interaction.GetWindowSelection(
new Point3d(0, 0, 0),
new Point3d(100, 100, 0)
);
```
#### 视图操作
```csharp
// 高亮对象
Interaction.HighlightObjects(entityIds);
// 缩放对象
Interaction.ZoomObjects(entityIds);
// 取消高亮
Interaction.UnhighlightObjects(entityIds);
```
### 🎨 实体绘制 (Draw)
提供各种几何实体的绘制功能,自动添加到当前空间。
#### 基本几何体
```csharp
// 绘制直线
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);
```
#### 复杂几何体
```csharp
// 绘制椭圆
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);
```
#### 块操作
```csharp
// 插入块
ObjectId blockId = Draw.Insert("块名", position);
// 创建块
ObjectId newBlockId = Draw.Block(entityIds, "新块名");
// 从外部文件插入块
ObjectId externalBlockId = Draw.BlockInDwg("块名", "外部文件.dwg");
```
### 🔧 实体创建 (NoDraw)
创建实体但不添加到空间,用于复杂几何体构建。
```csharp
// 创建直线(不添加到空间)
Line line = NoDraw.Line(point1, point2);
// 创建圆(不添加到空间)
Circle circle = NoDraw.Circle(center, radius);
// 创建多段线(不添加到空间)
Polyline polyline = NoDraw.Polyline(points);
// 手动添加到空间
ObjectId entityId = line.AddToCurrentSpace();
```
### 🎯 动态交互 (Jig)
提供动态交互功能,支持实时预览和操作。
```csharp
// 动态插入实体
ObjectId entityId = Interaction.InsertEntity(entity, "指定插入点");
// 动态缩放插入
ObjectId scaledEntityId = Interaction.InsertScalingEntity(entity, basePoint, "指定对角点");
// 动态旋转插入
ObjectId rotatedEntityId = Interaction.InsertRotationEntity(entity, center, "指定方向");
```
### 📊 数据存储 (FlexDataStore)
灵活的数据存储系统,支持任意键值对。
```csharp
// 创建数据存储
var dataStore = new FlexDataStore(dictionaryId);
// 存储数据
dataStore.SetValue("name", "张三")
.SetValue("age", "25")
.SetValue("department", "工程部");
// 读取数据
string name = dataStore.GetValue("name");
string age = dataStore.GetValue("age");
```
### 🧮 算法工具 (Algorithms)
提供丰富的几何算法和数学计算功能。
#### 曲线操作
```csharp
// 获取点到曲线的距离
double distance = curve.GetDistToPoint(point);
// 获取曲线上的点
Point3d pointOnCurve = curve.GetPointAtDist(distance);
// 获取子曲线
Curve subCurve = curve.GetSubCurve(new Interv(start, end));
// 获取曲线上的点集合
IEnumerable points = curve.GetPoints(1.0); // 参数间隔1.0
```
#### 几何计算
```csharp
// 获取包围盒
Extents3d extents = entityIds.GetExtents();
// 获取中心点
Point3d center = extents.GetCenter();
// 扩展包围盒
Extents3d expanded = extents.Expand(1.5); // 扩展1.5倍
// 判断点是否在包围盒内
bool isInside = extents.IsPointIn(point);
```
#### 多段线操作
```csharp
// 判断是否自相交
bool isSelfIntersecting = polyline.IsSelfIntersecting();
// 获取质心
Point3d centroid = polyline.Centroid();
// 判断点是否在多段线内
bool isInside = polyline.IsPointIn(point);
// 连接多段线
Polyline joined = polyline1.PolyJoin(polyline2);
```
#### 向量计算
```csharp
// 计算角度
double angle = vector1.ZeroToPiAngleTo(vector2);
// 计算叉积
double cross = vector1.Kross(vector2);
// 向量转换
Vector3d vector3d = vector2d.ToVector3d();
```
### 🔄 实体修改 (Modify)
提供实体变换和编辑功能。
#### 基本变换
```csharp
// 移动实体
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); // 复制镜像
```
#### 高级操作
```csharp
// 偏移曲线
ObjectId offsetId = curveId.Offset(distance, sidePoint);
// 打断曲线
ObjectId[] brokenIds = curveId.Break(point1, point2);
// 炸开实体
ObjectId[] explodedIds = entityId.Explode();
// 删除实体
entityId.Erase();
```
#### 组操作
```csharp
// 创建组
ObjectId groupId = entityIds.AddGroup("组名");
// 添加到组
Modify.AppendToGroup(groupId, entityId1, entityId2);
// 解组
Modify.Ungroup(groupId);
// 设置图层
entityId.SetLayer("图层名");
// 设置线型
entityId.SetLinetype("线型名", 1.0);
```
### 🛠️ 辅助工具 (Helper)
提供各种辅助功能。
#### 文件操作
```csharp
// 保存文件对话框
string savePath = Interaction.SaveFileDialogBySystem("保存文件", "默认文件名", "DWG文件|*.dwg");
// 打开文件对话框
string openPath = Interaction.OpenFileDialogBySystem("打开文件", "", "DWG文件|*.dwg");
// 选择文件夹
string folderPath = Interaction.FolderDialog("选择文件夹");
```
#### Excel操作 (NpoiHelper)
```csharp
// 读取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)
```csharp
// 字符串扩展方法
string result = StringHelper.SomeMethod(input);
```
#### 系统信息 (SystemHelper)
```csharp
// 获取系统信息
var systemInfo = SystemHelper.GetSystemInfo();
```
### 🎛️ Ribbon界面 (Ribbon)
支持自定义Ribbon界面。
#### 基本使用
```csharp
// 加载Ribbon菜单
RibbonMenuLoader.LoadRibbonMenu("RibbonMenu.xml");
// 处理命令
[CommandMethod("MyCommand")]
public void MyCommand()
{
// 命令实现
}
```
#### XML配置示例
```xml
```
### 📝 日志管理
```csharp
// 写入日志
LogManager.Write("操作信息");
// 创建日志表
var logTable = new LogTable(20, 30, 40);
string row = logTable.GetRow("列1", "列2", "列3");
```
### 🔧 工具类 (Utils)
提供通用工具方法。
```csharp
// 获取相对路径
string relativePath = Utils.GetRelativePath(basePath, fullPath);
// 解析INI文件
Dictionary> iniData = new Dictionary>();
bool success = Utils.ParseIniFile("config.ini", iniData);
```
## 🚀 性能优化
### 最佳实践
1. **使用事务管理**
```csharp
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 数据库操作
trans.Commit();
}
```
2. **批量操作**
```csharp
// 批量绘制
ObjectId[] entityIds = Draw.Line(points);
// 批量修改
entityIds.ForEach(id => id.SetLayer("图层名"));
```
3. **内存管理**
```csharp
// 及时释放资源
using (var entity = entityId.QOpenForRead())
{
// 使用实体
}
```
4. **避免频繁的数据库访问**
```csharp
// 缓存常用数据
var layerIds = DbHelper.GetAllLayerIds();
```
### 性能监控
```csharp
// 使用日志记录性能
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
// 执行操作
stopwatch.Stop();
LogManager.Write($"操作耗时: {stopwatch.ElapsedMilliseconds}ms");
```
## 🔧 扩展开发
### 自定义扩展方法
```csharp
public static class MyExtensions
{
public static void MyCustomMethod(this Entity entity)
{
// 自定义逻辑
}
public static ObjectId MyCustomDraw(this Point3d point)
{
// 自定义绘制逻辑
return Draw.Circle(point, 10);
}
}
```
### 自定义Jig
```csharp
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;
}
}
```
### 自定义命令
```csharp
[CommandMethod("MyCustomCommand")]
public void MyCustomCommand()
{
try
{
// 命令实现
Interaction.WriteLine("命令执行成功");
}
catch (Exception ex)
{
Interaction.WriteLine($"错误: {ex.Message}");
}
}
```
## 📋 开发规范
### 代码风格
1. **命名规范**
- 类名:PascalCase
- 方法名:PascalCase
- 变量名:camelCase
- 常量:UPPER_CASE
2. **注释规范**
```csharp
///
/// 方法功能描述
///
/// 参数说明
/// 返回值说明
public static ObjectId MyMethod(Point3d param)
{
// 实现代码
}
```
3. **异常处理**
```csharp
try
{
// 可能出错的代码
}
catch (System.Exception ex)
{
Interaction.WriteLine($"错误: {ex.Message}");
LogManager.Write($"异常: {ex}");
}
```
### 项目结构
```
NetCad/
├── Core/ # 核心功能
├── Extension/ # 扩展方法
├── Geometry/ # 几何计算
├── Helper/ # 辅助工具
├── Jig/ # 动态交互
├── Ribbon/ # 界面定制
└── Utils/ # 工具类
```
## 🐛 常见问题
### Q: 如何处理线程安全问题?
A: 使用 `App.LockAndExecute()` 方法进行线程安全操作:
```csharp
App.LockAndExecute(() => {
// 在这里进行AutoCAD操作
});
```
### Q: 如何获取实体的扩展数据?
A: 推荐使用新的 `FlexDataStore` 类:
```csharp
var dataStore = new FlexDataStore(dictionaryId);
dataStore.SetValue("key", "value");
```
### Q: 如何动态插入实体?
A: 使用 `Interaction.InsertEntity()` 方法:
```csharp
ObjectId entityId = Interaction.InsertEntity(entity, "指定插入点");
```
### Q: 如何处理大量实体的性能问题?
A: 使用批量操作和事务管理:
```csharp
App.LockAndExecute(() => {
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 批量操作
foreach (var entity in entities)
{
// 处理实体
}
trans.Commit();
}
});
```
### Q: 如何自定义Ribbon界面?
A: 修改 `RibbonMenu.xml` 文件并实现对应的命令方法。
## 📚 学习资源
### 官方文档
- [AutoCAD .NET API 文档](https://help.autodesk.com/view/OARX/2023/CHS/)
- [AutoCAD 开发者中心](https://www.autodesk.com/developer-network/platform-technologies/autocad)
### 示例项目
- [NetCad 示例](https://github.com/zhangfuwang666/NetCad/tree/main/examples)
- [AutoCAD 官方示例](https://github.com/Autodesk/AutoCAD-NET-Wizards)
### 社区资源
- [AutoCAD 开发者论坛](https://forums.autodesk.com/t5/autocad-forum/bd-p/78)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/autocad)
## 🤝 贡献指南
欢迎提交 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](LICENSE) 文件了解详情。
## 📞 联系方式
- **邮箱**: fuwang.zhang@qq.com
- **GitHub**: [zhangfuwang666](https://github.com/zhangfuwang666)
- **问题反馈**: [Issues](https://github.com/zhangfuwang666/NetCad/issues)
## 🙏 致谢
感谢所有为这个项目做出贡献的开发者!
---
⭐ 如果这个项目对您有帮助,请给它一个星标!
---
**注意**: 本项目仅供学习和研究使用,请遵守相关法律法规和AutoCAD使用协议。