cad.net Acad和Gcad系统变量和环境变量及反应器

获取系统变量和环境变量

#if !HC2020
using Acap = Autodesk.AutoCAD.ApplicationServices.Application;
#else
using Acap = GrxCAD.ApplicationServices.Application;
#endif
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

//环境变量例子
//http://www.theswamp.org/index.php?PHPSESSID=ec3e5da499ee486921c266b1b8c22966&topic=20237.msg362446#msg362446
namespace JoinBox
{
    public static partial class CadSystem
    {
#if NET35
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("acad.exe", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedGetEnv")]
        private static extern int AcedGetEnv(string envName, StringBuilder ReturnValue);

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("acad.exe", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedSetEnv")]
        private static extern int AcedSetEnv(string envName, StringBuilder NewValue);
#elif !HC2020
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("accore.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedGetEnv")]
        private static extern int AcedGetEnv(string envName, StringBuilder ReturnValue);

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("accore.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedSetEnv")]
        private static extern int AcedSetEnv(string envName, StringBuilder NewValue);
#endif

#if HC2020
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("gced.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "gcedGetEnv")]
        private static extern int AcedGetEnv(string envName, StringBuilder ReturnValue);

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("gced.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "gcedSetEnv")]
        private static extern int AcedSetEnv(string envName, StringBuilder NewValue);
#endif

        /// <summary>
        /// 获取系统变量值
        /// </summary>
        /// <param name="name">变量名</param>
        /// <returns>成功获取值,失败null</returns>
        public static string Getvar(string name)
        {
            try
            {
                return Acap.GetSystemVariable(name).ToString();
            }
            catch
            {
                return Getenv(name);
            }
        }

        /// <summary>
        /// 设置环境变量
        /// </summary>
        public static string Getenv(string name)
        {
            try
            {
                var sbRes = new StringBuilder(1024);
                AcedGetEnv(name, sbRes);
                return sbRes.ToString();
            }
            catch
            { }
            return null;
        }

        /// <summary>
        /// 设置系统或环境变量
        /// </summary>
        /// <param name="name">变量名</param>
        /// <param name="var">变量值</param>
        /// <returns>成功设置返回值,失败null</returns>
        public static string Setvar(string name, string var)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));
            if (var == null)
                throw new ArgumentNullException(nameof(var));

            string valueTypeName = null;
            string valueOld;
            try
            {
                //改系统变量
                var value = Acap.GetSystemVariable(name);
                if (value == null)
                    return null;
                valueOld = value.ToString();
                valueTypeName = value.GetType().Name;
                //如果出现了clayer无法设置,是没有锁文档导致的
                switch (valueTypeName)
                {
                    case "String":
                        Acap.SetSystemVariable(name, var.Replace("\"", ""));//去掉引号
                        break;
                    case "Double":
                        Acap.SetSystemVariable(name, double.Parse(var));
                        break;
                    case "Int16":
                        Acap.SetSystemVariable(name, short.Parse(var));
                        break;
                    case "Int32":
                        Acap.SetSystemVariable(name, int.Parse(var));
                        break;
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception err1)
            {
                try
                {
                    valueOld = Setenv(name, var, true); //改环境变量
                }
                catch (Autodesk.AutoCAD.Runtime.Exception err2)
                {
                    //当系统变量没有,环境变量也没有才抛出错误
                    var error = $"\n***********cad系统变量和环境都没有:" +
                        $"{name}\n出错:{var}\n来自:{valueTypeName}\n{err1.Message}\n{err2.Message}";
                    throw new Exception(error);
                }
            }
            return valueOld;
        }

        /// <summary>
        /// 设置环境变量
        /// </summary>
        /// <param name="name">lisp的名称</param>
        /// <param name="var">要设置的值</param>
        /// <returns></returns>
        public static string Setenv(string name, string var, bool isThrowError = false)
        {
            try
            {
                var oldVar = Getenv(name);
                var sbRes = new StringBuilder(var);
                AcedSetEnv(name, sbRes);
                return oldVar;
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                if (isThrowError)
                    throw e;
            }
            return null;
        }

        /// <summary>
        /// 返回现有系统变量并设置新系统变量
        /// </summary>
        /// <param name="pairs">设置的变量词典</param>
        /// <returns>返回现有变量词典</returns>
        public static Dictionary<string, string> SaveNowVar(Dictionary<string, string> pairs)
        {
            if (pairs == null)
                throw new ArgumentNullException(nameof(pairs));
            //系统变量保存
            var oldPairs = new Dictionary<string, string>();
            //系统变量设置
            foreach (var item in pairs)
            {
                var oldVar = Setvar(item.Key, item.Value);
                oldPairs.Add(item.Key, oldVar);
            }
            return oldPairs;
        }
    }
}

反应器

#if !HC2020
using SystemVariableChangedEventArgs = Autodesk.AutoCAD.ApplicationServices.SystemVariableChangedEventArgs;
using SystemVariableChangingEventArgs = Autodesk.AutoCAD.ApplicationServices.SystemVariableChangingEventArgs;
using Acap = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.Runtime;
#else
using SystemVariableChangedEventArgs = GrxCAD.ApplicationServices.SystemVariableChangedEventArgs;
using SystemVariableChangingEventArgs = GrxCAD.ApplicationServices.SystemVariableChangingEventArgs;
using Acap = GrxCAD.ApplicationServices.Application;
using GrxCAD.Runtime;
#endif
using System;

namespace JoinBox
{
    public class Reactor
    {
        //启用cad系统变量反应器
        [CommandMethod("SysGo")]
        public void SysGo()
        {
            Acap.SystemVariableChanging += AppSysVarChanging;
            Acap.SystemVariableChanged += AppSysVarChanged;
        }
        //禁用cad系统变量反应器
        [CommandMethod("SysEnd")]
        public void SysEnd()
        {
            Acap.SystemVariableChanging -= AppSysVarChanging;
            Acap.SystemVariableChanged -= AppSysVarChanged;
        }

        /// <summary>
        /// 事件:cad系统变量改变前
        /// </summary>
        public static void AppSysVarChanging(object senderObj, SystemVariableChangingEventArgs sysVarChEvtArgs)
        {
            object oVal = Acap.GetSystemVariable(sysVarChEvtArgs.Name);

            var dm = Acap.DocumentManager;
            var doc = dm.MdiActiveDocument;
            var ed = doc.Editor;
            ed.WriteMessage(Environment.NewLine + "改变前变量:" + sysVarChEvtArgs.Name + "旧值: " + oVal.ToString());
        }

        /// <summary>
        /// 事件:cad系统变量改变后
        /// </summary>
        public static void AppSysVarChanged(object senderObj, SystemVariableChangedEventArgs sysVarChEvtArgs)
        {
            object oVal = Acap.GetSystemVariable(sysVarChEvtArgs.Name);

            var dm = Acap.DocumentManager;
            var doc = dm.MdiActiveDocument;
            var ed = doc.Editor;
            ed.WriteMessage(Environment.NewLine + "改变后变量:" + sysVarChEvtArgs.Name + "新值: " + oVal.ToString());
        }
    }
}

(完)

posted @ 2019-01-02 17:02  惊惊  阅读(2136)  评论(2编辑  收藏  举报