注冊表自動加載.net程序集
通過修改注冊表的方式實現(xiàn).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內(nèi)部版本號,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骡送,執(zhí)行netload命令加載dll后運行RegisterMyApp命令后蔓肯,下次啟動后稚失,dll會自動加載搀绣,同時注冊表中會有相應(yīng)的項飞袋。如下圖所示:
執(zhí)行UnregisterMyApp命令后可以刪除RegDemo注冊表的相關(guān)內(nèi)容。
說明:
HostApplicationServices.Current.MachineRegistryProductRootKey返回的結(jié)果指向計算機\HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R20.1\ACAD-F001:804链患。