每一个小COM程序都往注册表里写了一堆东西,而没有反注册,所以觉得在main函数里每次手动注册与反注册比较好。
void RegisterDll() { char exeFileName[256]; ::GetModuleFileNameA(NULL, exeFileName, sizeof(exeFileName) / sizeof(char)); string str(exeFileName); string::size_type index = str.rfind('//'); assert(string::npos != index); string::iterator start = str.begin() + index; str.replace(start + 1, str.end(), "REGISTER.BAT"); ShellExecute(NULL, "open", str.c_str(), "-s", NULL, SW_HIDE); } void UnRegisterDll() { char exeFileName[256]; ::GetModuleFileNameA(NULL, exeFileName, sizeof(exeFileName) / sizeof(char)); string str(exeFileName); string::size_type index = str.rfind('//'); assert(string::npos != index); string::iterator start = str.begin() + index; str.replace(start + 1, str.end(), "UNREGISTER.BAT"); ShellExecute(NULL, "open", str.c_str(), "-s", NULL, SW_HIDE); }
上面二个函数即为注册与反注册,在main函数里调用。以后便不用手动双击“REGISTER.BAT".
实现上述功能的关键API:ShellExecute.具体用法可看MSDN了.
// // main function // int main() { RegisterDll(); // Initialize COM Library CoInitialize(NULL) ; trace("Get interface IX from Component 1.") ; IX* pIX = NULL ; HRESULT hr = ::CoCreateInstance(CLSID_Component1, NULL, CLSCTX_INPROC_SERVER, IID_IX, (void**)&pIX) ; if (SUCCEEDED(hr)) { trace("Succeeded creating component.") ; pIX->Fx() ; trace("Get interface IY from IX.") ; IY* pIY = NULL ; hr = pIX->QueryInterface(IID_IY, (void**)&pIY) ; if (SUCCEEDED(hr)) { trace("Succeeded getting interface IY from IX.") ; pIY->Fy() ; trace("Get interface IX from IY.") ; IX* pIX2 = NULL ; hr = pIY->QueryInterface(IID_IX, (void**)&pIX2); if (SUCCEEDED(hr)) { trace("Succeeded getting interface IX from IY.") ; pIX2->Release() ; } else { trace("Error! Should have gotten interface IX.") ; } pIY->Release() ; } else { trace("Could not get interface IY.") ; } pIX->Release() ; } else { std::cout << "Could not create component: " << std::hex << hr << std::endl ; } // Uninitialize COM Library CoUninitialize() ; UnRegisterDll(); system("pause"); return 0 ; }
似乎ShellExecute的功能远远比调用一个批处理要强大,我们在这里就只调用批处理。如果你在main当中调用当前进程EXE,这……
REGISTER.BAT:
@echo off rem rem Register.bat rem Registration file for Chapter 8 Example 2 rem echo on regsvr32 -s Cmpnt1.dll regsvr32 -s Cmpnt2.dll pause
UNREGISTER.BAT:
@echo off rem rem Register.bat rem Registration file for Chapter 8 Example 2 rem echo on regsvr32 -u -s Cmpnt1.dll regsvr32 -u -s Cmpnt2.dll pause