Visual C++ 7.1Visual C++ 8.0COMVisual C++ 7.0Windows 2003Windows 2000Visual C++ 6.0Windows XP中级开发Visual StudioWindowsC++
通过编码注册任何 COM 组件






1.91/5 (7投票s)
2005年4月13日

45052
通过代码注册任何 COM 组件。
引言
很多时候,当我们在应用程序中使用 COM 组件时,如果它未在系统注册或意外取消注册,我们的应用程序会在中间崩溃。因此,程序员养成在应用程序开始时重新注册 COM 组件是一个好习惯。
有时我们发现需要从代码中注册 DLL。因此,这段代码片段将帮助你通过将组件的绝对路径传递给函数来注册任何 DLL/OCX...
使用代码
将以下函数复制到你的代码中(作为全局函数),并按照如下所示调用该函数...
// //=================================================// //Developed By : Jigar Mehta //Date : [13/04/2005 11:08:16] //If returns Zero, DLL successfully registered... // -2 means DLL can not be loaded.. // -3 means DLL Entry point can not be found.. // -4 means Could not register the file... // DLL Registration failed.. //================================================// int RegisterComponent(char *absPath) { HINSTANCE hDLL = LoadLibrary(absPath); if(hDLL == NULL) { //-2 means DLL can not be loaded.. return -2; } typedef HRESULT (CALLBACK *HCRET)(void); HCRET lpfnDllRegisterServer; lpfnDllRegisterServer = (HCRET)GetProcAddress(hDLL, "DllRegisterServer"); if(lpfnDllRegisterServer == NULL) { //-3 means DLL Entry point can not be found.. return -3; } //Call the function by function pointer.. if(FAILED((*lpfnDllRegisterServer)())) { //-4 means Could not register the file... //DLL Registration failed.. return -4; } return 0; } //
如何调用此函数
// int nVal = RegisterComponent("C:\\ZButton.OCX"); if(nVal == 0) { AfxMessageBox("Component Successfully Registered..."); } else if(nVal == -2) { AfxMessageBox("DLL can not be loaded..\r\nReason could " "be path is incorrect\r\nor.. Component is corrupt"); } else if(nVal == -3) { AfxMessageBox("DLL Entrypoint for function " "DLLRegisterServer could not be found.."); } else if(nVal == -4) { AfxMessageBox("DLL Registration Failed.."); } else { AfxMessageBox("Unknown error in registering the file.."); } //
关注点
所以,只需使用正确的参数调用函数,DLL 就会被注册。祝你编码愉快!