二、自定义类AcVersion从注册表获取AutoCadCom库在GAC中的.Net程序集,以进行实际的反射,下面的代码主要应用于XP,如果在更高版本,你可能需要做些更改
- using System;
- using System.Collections.Generic;
- using Microsoft.Win32;
- using System.Text.RegularExpressions;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Runtime.InteropServices.ComTypes;
- namespace TlsCad.Common.Runtime
- {
- public class AcVersion
- {
- public int Major
- { private set; get; }
- public int Minor
- { private set; get; }
- public double ProgId
- {
- get { return Major + Minor / 10.0; }
- }
- public string ProductName
- { private set; get; }
- public string ProductRootKey
- { private set; get; }
- private string _appAssemblyName;
- private string _dbxAssemblyName;
- public Assembly AppAssembly
- { private set; get; }
- public Assembly DbxAssembly
- { private set; get; }
- static string _appClassNameHead = "Autodesk.AutoCAD.Interop.";
- static string _dbxClassNameHead = "Autodesk.AutoCAD.Interop.Common.";
- ///
- /// 获取Com对象的接口类型
- ///
- /// Com对象
- /// 接口类型
- public Type GetType(object obj)
- {
- IDispatch idisp = obj as IDispatch;
- ITypeInfo t;
- idisp.GetTypeInfo(0, 0, out t);
- string name = Marshal.GetTypeInfoName(t);
- return
- AppAssembly.GetType(_appClassNameHead + name) ??
- DbxAssembly.GetType(_dbxClassNameHead + name);
- }
- private static List _versions;
- public static List Versions
- {
- get
- {
- if (_versions == null)
- {
- string[] copys =
- Registry.LocalMachine
- .OpenSubKey(@"SOFTWARE\Autodesk\Hardcopy")
- .GetValueNames();
- _versions = new List();
- foreach (var rootkey in copys)
- {
- Regex r = new Regex(@"Autodesk\\AutoCAD\\R(\d+)\.(\d+)\\.*?");
- if (r.IsMatch(rootkey))
- {
- var gs = r.Match(rootkey).Groups;
- var ver =
- new AcVersion
- {
- ProductRootKey = rootkey,
- ProductName =
- Registry.LocalMachine
- .OpenSubKey("SOFTWARE")
- .OpenSubKey(rootkey)
- .GetValue("ProductName")
- .ToString(),
- Major = int.Parse(gs[1].Value),
- Minor = int.Parse(gs[2].Value),
- };
- ver.GetAssemblyName();
- _versions.Add(ver);
- }
- }
- }
- return _versions;
- }
- }
- public static AcVersion FromApp(dynamic app)
- {
- var gs = Regex.Match(app.Version, @"(\d+)\.(\d+).*?").Groups;
- int major = int.Parse(gs[1].Value);
- int minor = int.Parse(gs[2].Value);
- foreach (var ver in Versions)
- {
- if (ver.Major == major && ver.Minor == minor)
- return ver;
- }
- return null;
- }
- public void LoadAssembly()
- {
- AppAssembly = Assembly.Load(_appAssemblyName);
- DbxAssembly = Assembly.Load(_dbxAssemblyName);
- }
- private void GetAssemblyName()
- {
- _appAssemblyName = GetAssemblyName("AutoCad.Application", ProgId.ToString());
- _dbxAssemblyName = GetAssemblyName("ObjectDBX.AxDbDocument", Major.ToString());
- }
- private string GetAssemblyName(string name, string id)
- {
- string clsId =
- Registry.ClassesRoot
- .OpenSubKey(name + "." + id)
- .OpenSubKey("CLSID")
- .GetValue("")
- .ToString();
- return
- Registry.ClassesRoot
|