当前位置: 首页 > news >正文

JSON在AutoCAD二次开发中应用场景及具体案例

配置文件的读取

在AutoCAD插件开发中,可能需要生成、修改、读取配置文件中一些参数或设置。JSON格式的配置文件易于编写和修改,且可以方便地反序列化为对象进行使用。

运行后效果如下

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Newtonsoft.Json;
using System;
using System.IO;
using Path = System.IO.Path;
// AutoCAD 命令示例
public class ConfigCommands
{
    [CommandMethod("xx")]
    public void 加载文件配置()
    {
        Document doc = Application.DocumentManager.MdiActiveDocument;
        Editor ed = doc.Editor;

        // 加载配置
        AppConfig config = ConfigManager.LoadConfig();

        // 应用配置到图纸
        ConfigManager.ApplyConfigToDrawing(config);

        ed.WriteMessage($"\n已加载配置:默认图层 {config.DefaultLayer}");
    }

    [CommandMethod("tt")]
    public void 修改文件配置()
    {
        Document doc = Application.DocumentManager.MdiActiveDocument;
        Editor ed = doc.Editor;

        // 获取当前配置
        AppConfig config = ConfigManager.LoadConfig();

        // 修改配置示例
        config.DefaultLayer = "MyNewLayer";
        config.DefaultLineWeight = 0.5;

        // 保存配置
        ConfigManager.SaveConfig(config);

        ed.WriteMessage("\n配置已更新并保存");
    }
}
// 配置文件数据结构(示例)
public class AppConfig
{
    public string DefaultLayer { get; set; } = "0";      // 默认图层
    public double DefaultLineWeight { get; set; } = 0.3; // 默认线宽(毫米)
    public string[] RecentFiles { get; set; }            // 最近打开文件记录
    public ColorSetting Colors { get; set; }             // 颜色配置
}

public class ColorSetting
{
    public int Background { get; set; } = 16777215;     // 背景色(RGB白色)
    public int SelectionHighlight { get; set; } = 255;   // 选择高亮色(红色)
}

public static class ConfigManager
{
    private static readonly string ConfigPath = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        "MyAutoCADPlugin",
        "config.json"
    );

    /// <summary>
    /// 加载配置文件
    /// </summary>
    public static AppConfig LoadConfig()
    {
        try
        {
            // 如果配置文件不存在,创建默认配置
            if (!File.Exists(ConfigPath))
            {
                var defaultConfig = new AppConfig();
                SaveConfig(defaultConfig);
                return defaultConfig;
            }

            // 读取并反序列化JSON
            string json = File.ReadAllText(ConfigPath);
            return JsonConvert.DeserializeObject<AppConfig>(json);
        }
        catch (Exception ex)
        {
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(
                $"\n配置加载失败: {ex.Message}");
            return new AppConfig(); // 返回空配置
        }
    }

    /// <summary>
    /// 保存配置文件
    /// </summary>
    public static void SaveConfig(AppConfig config)
    {
        try
        {
            // 确保目录存在
            Directory.CreateDirectory(Path.GetDirectoryName(ConfigPath));

            // 序列化并保存
            string json = JsonConvert.SerializeObject(config, Formatting.Indented);
            File.WriteAllText(ConfigPath, json);
        }
        catch (Exception ex)
        {
            Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(
                $"\n配置保存失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 应用配置到当前图纸
    /// </summary>
    public static void ApplyConfigToDrawing(AppConfig config)
    {
        Database db = HostApplicationServices.WorkingDatabase;
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            try
            {
                // 获取层表
                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                // 检查默认图层是否存在
                if (!lt.Has(config.DefaultLayer))
                {
                    // 创建新图层
                    LayerTableRecord ltr = new LayerTableRecord
                    {
                        Name = config.DefaultLayer,
                        LineWeight = LineWeight.LineWeight030
                    };
                    lt.UpgradeOpen();
                    lt.Add(ltr);
                    tr.AddNewlyCreatedDBObject(ltr, true);
                }

                // 设置当前图层
                db.Clayer = lt[config.DefaultLayer];

                tr.Commit();
            }
            catch (Exception ex)
            {
                tr.Abort();
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(
                    $"\n配置应用失败: {ex.Message}");
            }
        }
    }
}

相关文章:

  • PHP 应用后台模块SessionCookieToken身份验证唯一性
  • 2025.3.17-2025.3.23学习周报
  • (UI自动化测试web端)第二篇:元素定位的方法_name定位
  • DeepSeek和Kimi在Neo4j中的表现
  • 教育装备展爆款产品:全息展示台+VR教育设备组合应用方案
  • 【自学笔记】智能合约基础知识点总览-持续更新
  • 如何使用命令行启动postgres数据库
  • 汇编语言习题笔记——第1章 汇编语言基础
  • 使用Doris broker load导入数据到带Kerberos的HA HDFS的命令详解
  • dns解析速度很快网页打开不了?
  • 5G通信协议相关
  • Leetcode 3494. Find the Minimum Amount of Time to Brew Potions
  • 网络编程--服务器双客户端聊天
  • 论文阅读:2023 arxiv Multiscale Positive-Unlabeled Detection of AI-Generated Texts
  • 从零构建大语言模型全栈开发指南:第二部分:模型架构设计与实现-2.1.2多头注意力扩展与掩码机制(因果掩码与填充掩码)
  • Qt中通过QLabel实时显示图像
  • 数据分析处理库-Pandas
  • 2.1.项目管理前言
  • 除了setup的表达方法,vue3还有什么表达方法
  • MySQL 处理重复数据:保留一条与两条的实现方案
  • 光大华夏:近代中国私立大学遥不可及的梦想
  • 上海一中院一审公开开庭审理被告人胡欣受贿案
  • 吴清:巴菲特即将退休,但价值投资、长期投资、理性投资、努力回报投资者等理念不会退休
  • 商务部:自5月7日起对原产于印度的进口氯氰菊酯征收反倾销税
  • 上海虹桥高铁站拦门事件反转,谁在带偏网友?
  • “高校领域突出问题系统整治”已启动,聚焦招生、基建、师德等重点