隐藏VS开发的程序目录下的DLL,可以将依赖的DLL放到指定位置去。
1.一直使用第三方控件,编译后依赖的控件都在运行目录,或者system32目录,看的很别扭,寻找过很多方法重定义加载,发现太复杂,最后无意间使用反射时发现,同一个DLL放在不同的地方只会被加载一次,因为每个dll都有一个唯一的KEY,利用这个方法,人为的加载这些DLL,可以从任意位置加载,可以解决程序运行目录下一堆DLL文件的问题。
这个方法只适用于反射方式加载的控件所依赖的DLL,不能对直接引用的DLL进行预加载。
//初始化加载一些用到的DLL文件
try
{
System::Reflection::Assembly::LoadFrom(USER_LIB.GetAppRunningDirectory() + "\\DLL\\DevComponents.DotNetBar2.dll"); //加载DLL
System::Reflection::Assembly::LoadFrom(USER_LIB.GetAppRunningDirectory() + "\\DLL\\DevExpress.Data.v14.2.dll"); //加载DLL
System::Reflection::Assembly::LoadFrom(USER_LIB.GetAppRunningDirectory() + "\\DLL\\DevExpress.Utils.v14.2.dll"); //加载DLL
System::Reflection::Assembly::LoadFrom(USER_LIB.GetAppRunningDirectory() + "\\DLL\\DevExpress.XtraEditors.v14.2.dll"); //加载DLL
System::Reflection::Assembly::LoadFrom(USER_LIB.GetAppRunningDirectory() + "\\DLL\\IPAddressControlLib.dll"); //加载DLL
}
catch (System::IO::FileNotFoundException^ e)
{
System::Windows::Forms::MessageBox::Show(e->Message, "加载控件错误,可能无法进行配置!",
System::Windows::Forms::MessageBoxButtons::OK, System::Windows::Forms::MessageBoxIcon::Error);
}
2.对直接依赖以及引用的DLL进行加载。
CLR会自动从运行目录或system32加载DLL,如果没有找到就会触发 AssemblyResolve 事件,在此事件中就可以自己去加载需要的DLL文件,返回给CLR.
using namespace System::Reflection;
Assembly^ MyResolveEventHandler(Object^ sender, ResolveEventArgs^ args); //申明
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
AppDomain^ currentDomain = AppDomain::CurrentDomain;
// 在创建任何控件之前启用 Windows XP 可视化效果
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
currentDomain->AssemblyResolve += gcnew ResolveEventHandler(MyResolveEventHandler);
// 创建主窗口并运行它
Application::Run(gcnew Form1());
return 0;
}
//缺少DLL文件加载的事件
static Assembly^ MyResolveEventHandler(Object^ sender, ResolveEventArgs^ args)
{
String ^dll_name;
AssemblyName^ myAssemblyName =
gcnew AssemblyName(args->Name);
Console::WriteLine("Resolving..." + myAssemblyName->Name);
dll_name = myAssemblyName->Name;
if (dll_name->IndexOf(".resources") < 0) //一个DLL文件会产生2次事件,比如abc.dll 第一次是abc,需要自己添加DLL扩展名,第二次会需要abc.resources,此时返回为空即可
{
dll_name += ".DLL";
}
else return nullptr; //resources返回为空即可
return Assembly::LoadFrom(USER_LIB.GetAppRunningDirectory() + "\\DLL\\" + dll_name);
}
Assembly::LoadFrom(USER_LIB.GetAppRunningDirectory() + "\\DLL\\" + dll_name);
这个就是从指定的位置加载DLL,可以更换为你自己定义的目录或者从资源文件中加载。