注册表自动加载.net程序集
通过修改注册表的方式实现.net程序的自动加载,注册程序的位置可以写入到计算机\HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R20.1\ACAD-F001:804\Applications目录下,或者计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Autodesk\AutoCAD\R20.1\ACAD-F001:804\Applications下 ,其中R20.1为AutoCad内部版本号,804代表中文版本。
namespace Demo1
{
public class Hello
{
[CommandMethod("RegisterMyApp")]
public void RegisterMyApp()
{
// 获取Applications在注册表中的key
string appKey = HostApplicationServices.Current.MachineRegistryProductRootKey;
string sAppName = "RegDemo";
RegistryKey regAcadProdKey = Registry.CurrentUser.OpenSubKey(appKey);
RegistryKey regAcadAppKey = regAcadProdKey.OpenSubKey("Applications", true);
//检查RegDemo键是否存在
string[] subKeys = regAcadAppKey.GetSubKeyNames();
foreach (string subKey in subKeys)
{
// 如果存在就退出
if (subKey.Equals(sAppName))
{
regAcadAppKey.Close();
return;
}
}
// 获取生成的dll文件位置
string sAssemblyPath = Assembly.GetExecutingAssembly().Location;
// 注册程序
RegistryKey regAppAddInKey = regAcadAppKey.CreateSubKey(sAppName);
regAppAddInKey.SetValue("DESCRIPTION", sAppName, Microsoft.Win32.RegistryValueKind.String);
regAppAddInKey.SetValue("LOADCTRLS", 14, Microsoft.Win32.RegistryValueKind.DWord);
regAppAddInKey.SetValue("LOADER", sAssemblyPath, Microsoft.Win32.RegistryValueKind.String);
regAppAddInKey.SetValue("MANAGED", 1, Microsoft.Win32.RegistryValueKind.DWord);
regAcadAppKey.Close();
}
[CommandMethod("UnregisterMyApp")]
public void UnregisterMyApp()
{
//计算机\HKEY_CURRENT_USER 下Software\Autodesk\AutoCAD\R20.1\ACAD-F001:804
string sProdKey = HostApplicationServices.Current.MachineRegistryProductRootKey;
string sAppName = "RegDemo";
RegistryKey regAcadProdKey = Registry.CurrentUser.OpenSubKey(sProdKey);
RegistryKey regAcadAppKey = regAcadProdKey.OpenSubKey("Applications", true);
//删除
regAcadAppKey.DeleteSubKeyTree(sAppName);
regAcadAppKey.Close();
}
}
}
程序运行后,首次启动AutoCad,执行netload命令加载dll后运行RegisterMyApp命令后,下次启动后,dll会自动加载,同时注册表中会有相应的项。如下图所示:
执行UnregisterMyApp命令后可以删除RegDemo注册表的相关内容。
说明:
HostApplicationServices.Current.MachineRegistryProductRootKey返回的结果指向计算机\HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R20.1\ACAD-F001:804。