static HRESULT UnregisterAddin(const std::wstring& clsid) { HRESULT hr = S_OK; ATL::CRegKey key; //delete BHO LSTATUS lStatus = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(clsid.c_str()); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } //delete HKCR lStatus = key.Open(HKEY_CLASSES_ROOT, L"CLSID"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(clsid.c_str()); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } return hr; }
BOOL CMailMsg::DetectMailClient(WTL::CString& sMailClientName) { ATL::CRegKey regKey; TCHAR buf[1024] = _T(""); ULONG buf_size = 0; LONG lResult; lResult = regKey.Open(HKEY_CURRENT_USER, _T("SOFTWARE\\Clients\\Mail"), KEY_READ); if(lResult!=ERROR_SUCCESS) { lResult = regKey.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Clients\\Mail"), KEY_READ); } if(lResult==ERROR_SUCCESS) { buf_size = 1023; #pragma warning(disable:4996) LONG result = regKey.QueryValue(buf, _T(""), &buf_size); #pragma warning(default:4996) if(result==ERROR_SUCCESS) { sMailClientName = buf; return TRUE; } regKey.Close(); } else { sMailClientName = "Not Detected"; } return FALSE; }
BOOL AddinHelper::TodayNotDo(const wchar_t* szValueName) { DWORD dwLastUTC = 0; BOOL bCando = FALSE; ATL::CRegKey key; if (key.Open(HKEY_CURRENT_USER, REGEDITPATH) == ERROR_SUCCESS) { bCando = TRUE; if(key.QueryDWORDValue(szValueName, dwLastUTC) == ERROR_SUCCESS) { __time64_t tTime = (__time64_t)dwLastUTC; tm* pTm = _localtime64(&tTime); LONG nLastDay = pTm->tm_mday; LONG nLastMonth = pTm->tm_mon; LONG nLastYear = pTm->tm_year; __time64_t lCurTime; _time64( &lCurTime); tm* pTmc = _localtime64(&lCurTime); LONG nCurDay = pTmc->tm_mday; LONG nCurMonth = pTmc->tm_mon; LONG nCurYear = pTmc->tm_year; TSDEBUG4CXX("TodayHasDo check time pTmc = "<<nCurYear<<nCurMonth<<nCurDay<<", pTm = "<<nLastYear<<nLastMonth<<nLastDay); if (nCurDay == nLastDay && nCurMonth == nLastMonth && nCurYear == nLastYear){ bCando = FALSE; } else{ bCando = TRUE; } } key.Close(); } return bCando; }
static HRESULT UnregisterAddin(const std::wstring& clsid) { HRESULT hr = S_OK; ATL::CRegKey key; //delete IconOverlay LSTATUS lStatus = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ShellIconOverlayIdentifiers"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(L" DeskUpdateRemind"); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } //delete CopyHook lStatus = key.Open(HKEY_CLASSES_ROOT, L"Directory\\shellex\\CopyHookHandlers"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(L"AYBSharing"); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } //delete BHO //lStatus = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects"); //if (lStatus == ERROR_SUCCESS) { // lStatus = key.RecurseDeleteKey(clsid.c_str()); // key.Close(); //} //if (lStatus != ERROR_SUCCESS) { // hr = HRESULT_FROM_WIN32(lStatus); //} //delete HKCR lStatus = key.Open(HKEY_CLASSES_ROOT, L"CLSID"); if (lStatus == ERROR_SUCCESS) { lStatus = key.RecurseDeleteKey(clsid.c_str()); key.Close(); } if (lStatus != ERROR_SUCCESS) { hr = HRESULT_FROM_WIN32(lStatus); } return hr; }
static HRESULT RegisterCopyHook(const std::wstring& clsid) { ATL::CRegKey key; std::wstring copyHookKey = L"Directory\\shellex\\CopyHookHandlers\\"; copyHookKey += L"AYBSharing"; LSTATUS lStatus = key.Create(HKEY_CLASSES_ROOT, copyHookKey.c_str()); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } lStatus = key.SetStringValue(NULL, clsid.c_str()); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } key.Close(); return S_OK; }
static HRESULT RegisterIconOverlay(const std::wstring& clsid) { ATL::CRegKey key; std::wstring iconOverlayKey = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ShellIconOverlayIdentifiers\\"; iconOverlayKey += L" DeskUpdateRemind"; LSTATUS lStatus = key.Create(HKEY_LOCAL_MACHINE, iconOverlayKey.c_str()); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } lStatus = key.SetStringValue(NULL, clsid.c_str()); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } key.Close(); return S_OK; }
static HRESULT RegisterClassRoot(const std::wstring& clsid, const std::wstring& dllPath) { ATL::CRegKey key; std::wstring inprocServerKey = L"CLSID\\" + clsid + L"\\InprocServer32"; LSTATUS lStatus = key.Create(HKEY_CLASSES_ROOT, inprocServerKey.c_str()); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } lStatus = key.SetStringValue(NULL, dllPath.c_str()); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } lStatus = key.SetStringValue(L"ThreadingModel", L"Apartment"); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } key.Close(); return S_OK; }
static HRESULT RegisterBho(const std::wstring& clsid) { ATL::CRegKey key; std::wstring bhoKey = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects\\"; bhoKey += clsid; LSTATUS lStatus = key.Create(HKEY_LOCAL_MACHINE, bhoKey.c_str()); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } lStatus = key.SetStringValue(NULL, L"YBBHO"); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } lStatus = key.SetDWORDValue(L"NoExplorer",1); if (lStatus != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(lStatus); } key.Close(); return S_OK; }
RegData AddinHelper::QueryRegVal(HKEY hkey, LPCTSTR lpszKeyName, LPCTSTR lpszValuename, REGSAM flag) { ATL::CRegKey key; HRESULT hr; RegData rd; if ((hr = key.Open(hkey, lpszKeyName, flag)) == ERROR_SUCCESS) { TCHAR tszValue[MAX_PATH] = {0}; ULONG lLen = MAX_PATH; DWORD dwInfo; if (key.QueryStringValue(lpszValuename, tszValue, &lLen) == ERROR_SUCCESS){ std::wstring wstrInfo = tszValue; rd.strData = wstrInfo; } else if((key.QueryDWORDValue(lpszValuename, dwInfo) == ERROR_SUCCESS)){ rd.dwData = dwInfo; } key.Close(); } return rd; }
void CCliOptionsForm::AssociateFileType() { TCHAR strExeLocation[MAX_PATH]; if (GetModuleFileName(NULL, strExeLocation, MAX_PATH)) { CPath pathExe(strExeLocation); pathExe.Canonicalize(); HKEY hKeyBase = HKEY_CURRENT_USER; if (DSUtil::IsUserAdmin()) hKeyBase = HKEY_LOCAL_MACHINE; // extension ATL::CRegKey regKey; CString strReg = _T("Software\\Classes\\.grfx"); if (ERROR_SUCCESS != regKey.Create(hKeyBase, strReg)) { DSUtil::ShowError(_T("Can't register file extension")); return; } regKey.SetStringValue(NULL, _T("GraphStudioNext.GraphFile.v1")); regKey.Close(); // FileType description strReg = _T("Software\\Classes\\GraphStudioNext.GraphFile.v1"); if (ERROR_SUCCESS != regKey.Create(hKeyBase, strReg)) { DSUtil::ShowError(_T("Can't register filetype")); return; } regKey.SetStringValue(NULL, _T("GraphStudioNext Filter Graph File")); regKey.Close(); // Open command strReg = _T("Software\\Classes\\GraphStudioNext.GraphFile.v1\\shell\\open\\command"); if (ERROR_SUCCESS != regKey.Create(hKeyBase, strReg)) { DSUtil::ShowError(_T("Can't register filetype open command")); return; } CString strOpen = pathExe; strOpen.Append(_T(" \"%1\"")); regKey.SetStringValue(NULL, strOpen); regKey.Close(); // Register Icon for the filetype strReg = _T("Software\\Classes\\GraphStudioNext.GraphFile.v1\\DefaultIcon"); if (ERROR_SUCCESS != regKey.Create(hKeyBase, strReg)) { DSUtil::ShowError(_T("Can't set the icon for the filetype")); return; } CString strIcon = pathExe; strIcon.Append(_T(",-129")); regKey.SetStringValue(NULL, strIcon); // Reload Shell with the new Icon SHChangeNotify(SHCNE_ASSOCCHANGED,NULL,NULL,NULL); DSUtil::ShowInfo(_T("FileType .grfx successfully registered.")); } }
void CCrashHandler::GenerateErrorReport(PEXCEPTION_POINTERS pExInfo) { CExceptionReport rpt(pExInfo); CMainDlg mainDlg; CZLib zlib; CString sTempFileName = CUtility::getTempFileName(); unsigned int i; // let client add application specific files to report if (m_lpfnCallback && !m_lpfnCallback(this)) return; //Определеяем, что делать с отчетом DumpType dumpType = Referenced;//По умолчанию сбрасываем только ту память, на которую идут ссылки в стеке ActionType actionType = GUI;//По умолчанию - выводим пользователю диалог CString action, storeFolder, dump; ATL::CRegKey rk; //Читаем из ключа с именем приложения int32_t lRet = rk.Open(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Cognitive Technologies Ltd.\\CuneiForm\\PumaCrashRpt\\") + CUtility::getAppName(), KEY_QUERY_VALUE); if(lRet != ERROR_SUCCESS) { //Читаем из дефолтного ключа lRet = rk.Open(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Cognitive Technologies Ltd.\\CuneiForm\\PumaCrashRpt\\Default"), KEY_QUERY_VALUE); } if(lRet == ERROR_SUCCESS) { //Читаем дейтсвие uint32_t dwBufLen = 1000; rk.QueryValue(action.GetBuffer(1000), "Action", &dwBufLen); action.ReleaseBuffer(MAX(dwBufLen - 1, 0)); //Читаем папку для автосохранения dwBufLen = 1000; rk.QueryValue(storeFolder.GetBuffer(1000), "StoreFolder", &dwBufLen); storeFolder.ReleaseBuffer(MAX(dwBufLen - 1, 0)); //Читаем тип дампа dwBufLen = 1000; rk.QueryValue(dump.GetBuffer(1000), "DumpType", &dwBufLen); dump.ReleaseBuffer(MAX(dwBufLen - 1, 0)); rk.Close(); if (!action.IsEmpty()) { if (action.CompareNoCase("GUI") == 0) actionType = GUI; else if (action.CompareNoCase("QuietStore") == 0) actionType = QuietStore; else if (action.CompareNoCase("NoAction") == 0) actionType = NoAction; } if (!dump.IsEmpty()) { if (dump.CompareNoCase("Mini") == 0) dumpType = Mini; else if (dump.CompareNoCase("Referenced") == 0) dumpType = Referenced; else if (dump.CompareNoCase("Full") == 0) dumpType = Full; } if (storeFolder.CompareNoCase("Temp folder") == 0) storeFolder = getenv("TEMP"); } if (actionType == NoAction) return; // add crash files to report m_files[rpt.getCrashFile(dumpType)] = CString((const char *)IDS_CRASH_DUMP); m_files[rpt.getCrashLog()] = CString((const char *)IDS_CRASH_LOG); // add symbol files to report for (i = 0; i < (uint)rpt.getNumSymbolFiles(); i++) m_files[(const char *)rpt.getSymbolFile(i)] = CString((const char *)IDS_SYMBOL_FILE); // zip the report if (!zlib.Open(sTempFileName)) return; // add report files to zip TStrStrMap::iterator cur = m_files.begin(); for (i = 0; i < m_files.size(); i++, cur++) zlib.AddFile((*cur).first); zlib.Close(); if (actionType == GUI) { // display main dialog mainDlg.m_pUDFiles = &m_files; //Сохраняем флаги по исключениям с плавающей точкой - кто-то их злобно сбрасывает при показе диалога uint oldFpState = _controlfp(0, 0); if (IDOK == mainDlg.DoModal()) { if (m_sTo.IsEmpty() || !MailReport(rpt, sTempFileName, mainDlg.m_sEmail, mainDlg.m_sDescription)) { SaveReport(rpt, sTempFileName); } } //Восстанавливаем флаги _controlfp(oldFpState, _MCW_DN | _MCW_EM | _MCW_IC | _MCW_RC | _MCW_PC); } else if (actionType == QuietStore) { // Just in-case it already exist ::DeleteFile(storeFolder + '\\' + CUtility::formatSaveFileName() + ".zip"); ::CopyFile(sTempFileName, storeFolder + '\\' + CUtility::formatSaveFileName() + ".zip", TRUE); } DeleteFile(sTempFileName); }
void AddinHelper::LaunchExe() { TSDEBUG4CXX("LaunchExe , enter Now = "<<::GetTickCount()); BOOL bFirst = TodayNotDo(); if (bFirst){ SendState::Send("explorerplugin_startup", "explorerplugin"); } else{ SendState::Send("explorerplugin_timer", "explorerplugin"); } //判断地域标志 DWORD dwLastUTC = 0; DWORD dwZoneAllow = 0; BOOL bCando = FALSE; ATL::CRegKey key; if (!bFirst && key.Open(HKEY_CURRENT_USER, REGEDITPATH) == ERROR_SUCCESS) { bCando = TRUE; if (key.QueryDWORDValue(ZONESWITCH, dwZoneAllow) != ERROR_SUCCESS || dwZoneAllow != 1){ bCando = FALSE; } else if(key.QueryDWORDValue(LASTLAUNCHUTC, dwLastUTC) == ERROR_SUCCESS) { __time64_t tTime = (__time64_t)dwLastUTC; tm* pTm = _localtime64(&tTime); LONG nLastDay = pTm->tm_mday; LONG nLastMonth = pTm->tm_mon; LONG nLastYear = pTm->tm_year; __time64_t lCurTime; _time64( &lCurTime); tm* pTmc = _localtime64(&lCurTime); LONG nCurDay = pTmc->tm_mday; LONG nCurMonth = pTmc->tm_mon; LONG nCurYear = pTmc->tm_year; TSDEBUG4CXX("check time pTmc = "<<nCurYear<<nCurMonth<<nCurDay<<", pTm = "<<nLastYear<<nLastMonth<<nLastDay); if (nCurDay == nLastDay && nCurMonth == nLastMonth && nCurYear == nLastYear){ bCando = FALSE; } else{ bCando = TRUE; } } key.Close(); } TSDEBUG4CXX("LaunchExe , bCando = "<<bCando); if (!bFirst && !bCando){ return; } if (!bFirst && IsStartUp()){ return; } RegData rd = QueryRegVal(HKEY_LOCAL_MACHINE, REGEDITPATH, _T("Path"), KEY_READ | KEY_WOW64_32KEY); TSDEBUG4CXX("LaunchExe rd.strData = "<<rd.strData.c_str()); if (rd.strData == L"" || !PathFileExists(rd.strData.c_str())){ return; } TCHAR* tszProName = PathFindFileName(rd.strData.c_str()); if (!bFirst && QueryProcessExist(tszProName)){ TSDEBUG4CXX("LaunchExe process exist "<<tszProName); return; } SHELLEXECUTEINFO sei; std::memset(&sei, 0, sizeof(SHELLEXECUTEINFO)); sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.lpFile = rd.strData.c_str(); sei.lpParameters = L"/sstartfrom explorerplugin /embedding"; sei.nShow = SW_SHOWNORMAL; ShellExecuteEx(&sei); TSDEBUG4CXX("LaunchExe rd.strData.c_str() = "<<rd.strData.c_str()); if (bFirst){ ATL::CRegKey key; if (key.Open(HKEY_CURRENT_USER, REGEDITPATH) == ERROR_SUCCESS) { __time64_t lCurTime; _time64( &lCurTime); key.SetDWORDValue(L"pluginlastutc", lCurTime); key.Close(); } } }
void CFileTypesForm::OnBnClickedButtonReload() { for (DWORD i=0; i<pageCount; i++) { if (pages[i]) { pages[i]->info.Clear(); pages[i]->UpdateTree(); } } DSUtil::FilterTemplates filters; filters.EnumerateAllRegisteredFilters(); // search for registered protocols if (page_protocols) { ATL::CRegKey rkRoot(HKEY_CLASSES_ROOT); // only real protocols => not something like "WMP11.AssocProtocol.MMS" // faster, because i don't need to search in every entry for "Source Filter" TCHAR szName[10] = {0}; DWORD szNameLength = 10; DWORD i = 0; long ret = 0; while (ERROR_NO_MORE_ITEMS != (ret = rkRoot.EnumKey(i++, szName, &szNameLength))) { if (ret != ERROR_SUCCESS) continue; CRegKey rkKey; if(ERROR_SUCCESS == rkKey.Open(HKEY_CLASSES_ROOT, szName, KEY_READ)) { TCHAR szSourceFilterGuid[40] = {0}; DWORD szLength = 40; if (ERROR_SUCCESS == rkKey.QueryStringValue(_T("Source Filter"), szSourceFilterGuid, &szLength)) { GraphStudio::PropItem* group = new GraphStudio::PropItem(CString(szName)); CString strClsid = szSourceFilterGuid; GUID clsid = {0}; CLSIDFromString((LPOLESTR)strClsid.GetBuffer(), &clsid); group->AddItem(new GraphStudio::PropItem(_T("CLSID"), CString(szSourceFilterGuid), false)); DSUtil::FilterTemplate ft; if (filters.FindTemplateByCLSID(clsid, &ft)) { group->AddItem(new GraphStudio::PropItem(_T("Name"), CString(ft.name), false)); group->AddItem(new GraphStudio::PropItem(_T("File"), CString(ft.file), false)); } // last Change of this key FILETIME timeMod = {0}; if (ERROR_SUCCESS == RegQueryInfoKey(rkKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &timeMod)) group->AddItem(new GraphStudio::PropItem(_T("Modified"), CTime(timeMod))); page_protocols->info.AddItem(group); } } rkKey.Close(); szNameLength = 10; } page_protocols->UpdateTree(); rkRoot.Close(); } // search for registered extensions if (page_extensions) { ATL::CRegKey rkRoot; CString strRoot = _T("Media Type\\Extensions"); if (ERROR_SUCCESS == rkRoot.Open(HKEY_CLASSES_ROOT, strRoot, KEY_READ)) { // {7DF62B50-6843-11D2-9EEB-006008039E37} static const GUID CLSID_StillVideo = {0x7DF62B50, 0x6843, 0x11D2, { 0x9E, 0xEB, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37} }; TCHAR szName[50] = {0}; DWORD szNameLength = 50; DWORD i = 0; while (ERROR_NO_MORE_ITEMS != rkRoot.EnumKey(i++, szName, &szNameLength)) { CString strKey = strRoot; strKey.Append(_T("\\")); strKey.Append(szName); CRegKey rkKey; if(ERROR_SUCCESS == rkKey.Open(HKEY_CLASSES_ROOT, strKey, KEY_READ)) { GraphStudio::PropItem* group = new GraphStudio::PropItem(CString(szName)); TCHAR szGuid[40] = {0}; DWORD szLength = 40; if (ERROR_SUCCESS == rkKey.QueryStringValue(_T("Source Filter"), szGuid, &szLength)) { CString strClsid = szGuid; GUID clsid = {0}; CLSIDFromString((LPOLESTR)strClsid.GetBuffer(), &clsid); group->AddItem(new GraphStudio::PropItem(_T("CLSID"), CString(szGuid), false)); DSUtil::FilterTemplate ft; if (filters.FindTemplateByCLSID(clsid, &ft)) { group->AddItem(new GraphStudio::PropItem(_T("Name"), CString(ft.name), false)); group->AddItem(new GraphStudio::PropItem(_T("File"), CString(ft.file), false)); } else if (clsid == CLSID_StillVideo) { group->AddItem(new GraphStudio::PropItem(_T("Name"), _T("Generate Still Video"), false)); } } szLength = 40; if (ERROR_SUCCESS == rkKey.QueryStringValue(_T("Media Type"), szGuid, &szLength)) { CString strMT; GUID clsidMT = {0}; CLSIDFromString((LPOLESTR)strMT.GetBuffer(), &clsidMT); GraphStudio::NameGuid(clsidMT,strMT,CgraphstudioApp::g_showGuidsOfKnownTypes); group->AddItem(new GraphStudio::PropItem(_T("MediaType"), strMT, false)); } szLength = 40; if (ERROR_SUCCESS == rkKey.QueryStringValue(_T("SubType"), szGuid, &szLength)) { CString strST = szGuid; GUID clsidST = {0}; CLSIDFromString((LPOLESTR)strST.GetBuffer(), &clsidST); GraphStudio::NameGuid(clsidST,strST,CgraphstudioApp::g_showGuidsOfKnownTypes); group->AddItem(new GraphStudio::PropItem(_T("SubType"), strST, false)); } // last Change of this key FILETIME timeMod = {0}; if (ERROR_SUCCESS == RegQueryInfoKey(rkKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &timeMod)) group->AddItem(new GraphStudio::PropItem(_T("Modified"), CTime(timeMod))); page_extensions->info.AddItem(group); } rkKey.Close(); szNameLength = 50; } page_extensions->UpdateTree(); } rkRoot.Close(); } // search for registered byte pattern if (page_bytes) { ATL::CRegKey rkRoot; CString strRoot = _T("Media Type"); if (ERROR_SUCCESS == rkRoot.Open(HKEY_CLASSES_ROOT, strRoot, KEY_READ)) { TCHAR szMTName[40] = {0}; DWORD szMTNameLength = 40; DWORD i = 0; while (ERROR_NO_MORE_ITEMS != rkRoot.EnumKey(i++, szMTName, &szMTNameLength)) { CString strMT = szMTName; GUID clsidMT = {0}; if(NOERROR == CLSIDFromString((LPOLESTR)strMT.GetBuffer(), &clsidMT)) { GraphStudio::NameGuid(clsidMT,strMT,false); CString strKeyMT = strRoot; strKeyMT.Append(_T("\\")); strKeyMT.Append(szMTName); CRegKey rkKeyMT; if(ERROR_SUCCESS == rkKeyMT.Open(HKEY_CLASSES_ROOT, strKeyMT, KEY_READ)) { TCHAR szSTName[40] = {0}; DWORD szSTNameLength = 40; DWORD j = 0; while (ERROR_NO_MORE_ITEMS != rkKeyMT.EnumKey(j++, szSTName, &szSTNameLength)) { CString strST = szSTName; GUID clsidST = {0}; if(NOERROR == CLSIDFromString((LPOLESTR)strST.GetBuffer(), &clsidST)) { GraphStudio::NameGuid(clsidST,strST,false); CString strKeyST = strKeyMT; strKeyST.Append(_T("\\")); strKeyST.Append(szSTName); CRegKey rkKeyST; if(ERROR_SUCCESS == rkKeyST.Open(HKEY_CLASSES_ROOT, strKeyST, KEY_READ)) { TCHAR szGuid[40] = {0}; DWORD szLength = 40; if (ERROR_SUCCESS == rkKeyST.QueryStringValue(_T("Source Filter"), szGuid, &szLength)) { CString groupName = strMT; groupName.Append(_T("\\")); groupName.Append(strST); GraphStudio::PropItem* group = new GraphStudio::PropItem(groupName); CString strClsid = szGuid; GUID clsid = {0}; CLSIDFromString((LPOLESTR)strClsid.GetBuffer(), &clsid); group->AddItem(new GraphStudio::PropItem(_T("CLSID"), CString(szGuid), false)); DSUtil::FilterTemplate ft; if (filters.FindTemplateByCLSID(clsid, &ft)) { group->AddItem(new GraphStudio::PropItem(_T("Name"), CString(ft.name), false)); group->AddItem(new GraphStudio::PropItem(_T("File"), CString(ft.file), false)); } // Enumerate the values TCHAR szValueName[5] = {0}; DWORD szValueNameLength = 5; DWORD dwRegType; DWORD k = 0; long ret = 0; while (ERROR_NO_MORE_ITEMS != (ret = RegEnumValue(rkKeyST, k++, szValueName, &szValueNameLength, NULL, &dwRegType, NULL, NULL))) { if (dwRegType == REG_SZ && ret == ERROR_SUCCESS) { TCHAR szValue[255] = {0}; DWORD szValueLength = 255; if (ERROR_SUCCESS == rkKeyST.QueryStringValue(szValueName, szValue, &szValueLength)) { CString strValue = szValue; CStringArray arValues; DSUtil::Tokenizer(strValue, _T(","), arValues); CString strResultValue; bool lastTokenWasEmpty = false; for (int i=0; i<arValues.GetCount(); i++) { CString strToken = arValues.GetAt(i); strToken = strToken.Trim(); switch (i % 4) { case 0: if (i > 0) strResultValue.Append(_T(" && [")); else strResultValue.Append(_T("[")); strResultValue.Append(strToken); break; case 1: strResultValue.Append(_T(",")); strResultValue.Append(strToken); break; case 2: strResultValue.Append(_T("] => (")); strResultValue.Append(ByteFormatString(strToken)); break; case 3: if (!lastTokenWasEmpty) strResultValue.Append(_T(" = ")); strResultValue.Append(ByteFormatString(strToken)); strResultValue.Append(_T(")")); break; } lastTokenWasEmpty = strToken.IsEmpty(); } group->AddItem(new GraphStudio::PropItem(CString(szValueName), strResultValue, false)); // TODO maybe better format of the byte string } } szValueNameLength = 5; } // last Change of this key FILETIME timeMod = {0}; if (ERROR_SUCCESS == RegQueryInfoKey(rkKeyST, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &timeMod)) group->AddItem(new GraphStudio::PropItem(_T("Modified"), CTime(timeMod))); page_bytes->info.AddItem(group); } } rkKeyST.Close(); } szSTNameLength = 40; } } rkKeyMT.Close(); } szMTNameLength = 40; } page_bytes->UpdateTree(); } rkRoot.Close(); } }
HRESULT UninstallService() { TSAUTO(); ATL::CRegKey key; LSTATUS lRegResult = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost"); if(lRegResult == ERROR_SUCCESS) { lRegResult = key.DeleteValue(L"ADCleanService"); if(lRegResult != ERROR_SUCCESS) { TSWARN4CXX("Failed to delete reg value. Key: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost\\ADCleanService. Error: " << lRegResult); } key.Close(); } else { TSWARN4CXX("Failed to open reg key. Key: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost. Error: " << lRegResult); } lRegResult = key.Open(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\services\\ADCleanService"); if(lRegResult == ERROR_SUCCESS) { lRegResult = key.RecurseDeleteKey(L"Parameters"); if(lRegResult != ERROR_SUCCESS) { TSWARN4CXX("Failed to delete reg key. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService\\Parameters. Error: " << lRegResult); } key.Close(); } else { TSWARN4CXX("Failed to open reg key. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService. Error: " << lRegResult); } SC_HANDLE schSCManager = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if(schSCManager == NULL) { DWORD dwOpenError = ::GetLastError(); TSERROR4CXX("OpenSCManager failed. Error: " << dwOpenError); return HRESULT_FROM_WIN32(dwOpenError); } ScopeResourceHandle<SC_HANDLE, BOOL (WINAPI*)(SC_HANDLE)> autoCloseSCManagerHandle(schSCManager, ::CloseServiceHandle); SC_HANDLE schService = ::OpenService(schSCManager, szServiceName, DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS); if(schService == NULL) { DWORD dwOpenError = ::GetLastError(); TSERROR4CXX("OpenSCManager failed. Error: " << dwOpenError); return HRESULT_FROM_WIN32(dwOpenError); } ScopeResourceHandle<SC_HANDLE, BOOL (WINAPI*)(SC_HANDLE)> autoCloseServiceHandle(schService, ::CloseServiceHandle); SERVICE_STATUS_PROCESS ssp; DWORD dwBytesNeeded = 0; if(!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { DWORD dwQueryServiceStatus = ::GetLastError(); TSERROR4CXX("QueryServiceStatusEx failed. Error: " << dwQueryServiceStatus); return HRESULT_FROM_WIN32(dwQueryServiceStatus); } if(ssp.dwCurrentState != SERVICE_STOPPED) { DWORD dwStartTime = GetTickCount(); DWORD dwTimeout = 30000; while (ssp.dwCurrentState == SERVICE_STOP_PENDING) { DWORD dwWaitTime = ssp.dwWaitHint / 10; if( dwWaitTime < 1000 ) dwWaitTime = 1000; else if ( dwWaitTime > 10000 ) dwWaitTime = 10000; Sleep(dwWaitTime); if(!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { DWORD dwQueryServiceStatus = ::GetLastError(); TSERROR4CXX("QueryServiceStatusEx failed. Error: " << dwQueryServiceStatus); return HRESULT_FROM_WIN32(dwQueryServiceStatus); } if(ssp.dwCurrentState == SERVICE_STOPPED) { TSINFO4CXX("Service Stop Success."); goto AfterStopLabel; } if(GetTickCount() - dwStartTime > dwTimeout) { TSERROR4CXX("Wait for service stop timeout."); return E_FAIL; } } if(!ControlService(schService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&ssp)) { DWORD dwControlServiceError = ::GetLastError(); TSERROR4CXX("ControlService failed. Error: " << dwControlServiceError); return HRESULT_FROM_WIN32(dwControlServiceError); } while ( ssp.dwCurrentState != SERVICE_STOPPED ) { DWORD dwWaitTime = ssp.dwWaitHint; if( dwWaitTime < 1000 ) dwWaitTime = 1000; else if ( dwWaitTime > 10000 ) dwWaitTime = 10000; Sleep(dwWaitTime); if(!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { DWORD dwQueryServiceStatus = ::GetLastError(); TSERROR4CXX("QueryServiceStatusEx failed. Error: " << dwQueryServiceStatus); return HRESULT_FROM_WIN32(dwQueryServiceStatus); } if(ssp.dwCurrentState == SERVICE_STOPPED) { TSINFO4CXX("Service Stop Success."); break; } if(GetTickCount() - dwStartTime > dwTimeout ) { TSERROR4CXX("Wait timed out"); return E_FAIL; } } } AfterStopLabel: if(::DeleteService(schService)) { TSERROR4CXX("DeleteService success"); return S_OK; } else { DWORD dwDeleteError = ::GetLastError(); TSERROR4CXX("DeleteService failed. Error: " << dwDeleteError); return HRESULT_FROM_WIN32(dwDeleteError); } }
HRESULT CreateGreenShieldService(const wchar_t* szDllPath) { TSAUTO(); SC_HANDLE schSCManager = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (schSCManager == NULL) { DWORD dwOpenError = ::GetLastError(); TSERROR4CXX("OpenSCManager failed. Error: " << dwOpenError); return HRESULT_FROM_WIN32(dwOpenError); } ScopeResourceHandle<SC_HANDLE, BOOL (WINAPI*)(SC_HANDLE)> autoCloseSCManagerHandle(schSCManager, ::CloseServiceHandle); const wchar_t* szImagePath = L"%SystemRoot%\\System32\\svchost.exe -k ADCleanService"; SC_HANDLE schService = ::CreateService( schSCManager, szServiceName, szServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_SHARE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szImagePath, NULL, NULL, NULL, NULL, NULL); if(schService == NULL) { DWORD dwCreateError = ::GetLastError(); TSERROR4CXX("CreateService failed. Error: " << dwCreateError); return HRESULT_FROM_WIN32(dwCreateError); } ScopeResourceHandle<SC_HANDLE, BOOL (WINAPI*)(SC_HANDLE)> autoCloseServiceHandle(schService, ::CloseServiceHandle); SERVICE_DESCRIPTION description = { L"广告清道夫实时过滤服务。" }; ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &description); // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ADCleanService ATL::CRegKey key; LONG lRegResult = key.Open(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\services\\ADCleanService", KEY_READ); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Filed to open reg key. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } key.Close(); // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ADCleanService\Parameters lRegResult = key.Create(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\services\\ADCleanService\\Parameters"); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Failed to create reg key. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService\\Parameters. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } lRegResult = key.SetStringValue(L"ServiceDll", szDllPath, REG_EXPAND_SZ); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Failed to set reg value. Key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\ADCleanService\\Parameters\\ServiceDll. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } key.Close(); // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost lRegResult = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost"); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Failed to open reg key. Key: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } lRegResult = key.SetMultiStringValue(L"ADCleanService", L"ADCleanService\0"); if(lRegResult != ERROR_SUCCESS) { TSERROR4CXX("Failed to set reg value. Key: HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost\\ADCleanService. Error: " << lRegResult); return HRESULT_FROM_WIN32(lRegResult); } // start service ::StartService(schService, 0, NULL); return S_OK; }