Introduction
Many a times, it happens that when we are using COM components in our application and if it is not registered with the system or unregistered accidentally, our application breaks in the middle.. So, it is a good habit for a programmer to re-register the COM components in the beginning of the application..
Sometimes we find the need to register DLLs from the code.. So, this code snippet will help you register any DLL/OCX by just passing the absolute path of the component into the function...
Using the code
Copy the following function into your code (as a global function) and call that function as shown below...
int RegisterComponent(char *absPath)
{
HINSTANCE hDLL = LoadLibrary(absPath);
if(hDLL == NULL)
{
return -2;
}
typedef HRESULT (CALLBACK *HCRET)(void);
HCRET lpfnDllRegisterServer;
lpfnDllRegisterServer =
(HCRET)GetProcAddress(hDLL, "DllRegisterServer");
if(lpfnDllRegisterServer == NULL)
{
return -3;
}
if(FAILED((*lpfnDllRegisterServer)()))
{
return -4;
}
return 0;
}
How to call this function:
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..");
}
Points of Interest
So, it's just calling the function with proper arguments and the DLL will be registered.. Happy coding..