using System;
using Microsoft.Win32;
namespace TFlexControlSample
{
class APILoader : IDisposable
{
private string _cadPath = null;
private bool _initialized = false;
//прописываем путь к CADу
public APILoader()
{
_cadPath = GetPath("T-FLEX CAD 3D 14", "Rus");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);
}
public bool InitializeTFlexCADAPI()
{
if (_initialized)
return true;
if (string.IsNullOrEmpty(_cadPath))
throw new System.IO.FileNotFoundException("T-FLEX CAD is not installed");
//Перед работой с API T-FLEX CAD его необходимо инициализировать
//В зависимости от параметров инициализации, будут или не будут
//доступны функции изменения документов и сохранение документов в файл.
//За это отвечает параметр setup.ReadOnly.
//Если setup.ReadOnly = false, то для работы программы требуется
//лицензия на сам T-FLEX CAD
TFlex.ApplicationSessionSetup setup = new TFlex.ApplicationSessionSetup();
setup.ReadOnly = false;
_initialized = TFlex.Application.InitSession(setup);
return _initialized;
}
public void Dispose()
{
if (_initialized)
{
TFlex.Application.ExitSession();
_initialized = false;
}
}
private static string GetPath(string productName, string language)
{
if (string.IsNullOrEmpty(productName) || string.IsNullOrEmpty(language))
return null;
string fullProductName = UIntPtr.Size == 8 ? productName + " x64" : productName;
string regPath = string.Format(@"SOFTWARE\Top Systems\{0}\{1}", fullProductName, language);
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(regPath,
RegistryKeyPermissionCheck.ReadSubTree,
System.Security.AccessControl.RegistryRights.ReadKey))
{
if (key == null)
return null;
string path = (string)key.GetValue("ProgramFolder", string.Empty);
if (string.IsNullOrEmpty(path))
{
path = (string)key.GetValue("SetupHelpPath", string.Empty);
if (string.IsNullOrEmpty(path))
return null;
}
if (!path.EndsWith("\\"))
path += "\\";
return path;
}
}
private System.Reflection.Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
if (string.IsNullOrEmpty(_cadPath))
return null;
try
{
string name = args.Name;
int index = name.IndexOf(",");
if (index > 0)
name = name.Substring(0, index);
string fileName = string.Format("{0}{1}.dll", _cadPath, name);
if (!System.IO.File.Exists(fileName))
return null;
System.IO.Directory.SetCurrentDirectory(_cadPath);
return System.Reflection.Assembly.LoadFile(fileName);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(string.Format("Ошибка загрузки сборки {0}:\n{1}", args.Name, ex.Message),
"Ошибка",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
return null;
}
}
}
}