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; }
/// Loads a list of message IDs that should be passed on to the AOIA application void LoadMessageFilter(HKEY hKeyParent, LPCTSTR lpszKeyName) { g_messageFilter.empty(); ATL::CRegKey reg; if (reg.Open(hKeyParent, lpszKeyName, KEY_READ) == ERROR_SUCCESS) { TCHAR subkey[256]; DWORD skLength = 256; DWORD dw; int index = 0; while (true) { if (reg.EnumKey(index, subkey, &skLength) == ERROR_SUCCESS) { index++; if (reg.QueryDWORDValue(subkey, dw) == ERROR_SUCCESS) { g_messageFilter.insert(dw); } } else { break; } } } else { LOG("Unable to open key: " << lpszKeyName) } }
bool RegistryHelper::writeValue(const LPTSTR valueName, std::wstring const& value) const { ATL::CRegKey regKey; return (ERROR_SUCCESS == regKey.Open(key_, keyName_, KEY_WRITE) || ERROR_SUCCESS == regKey.Create(key_, keyName_, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE)) && ERROR_SUCCESS == regKey.SetStringValue(valueName, value.c_str()); }
bool GetGreenShiledExeFilePath(wchar_t* buffer, std::size_t bufferLength) { ATL::CRegKey key; if(key.Open(HKEY_LOCAL_MACHINE, L"Software\\ADClean", KEY_QUERY_VALUE) != ERROR_SUCCESS) { return false; } ULONG size = bufferLength; return key.QueryStringValue(L"Path", buffer, &size) == ERROR_SUCCESS; }
CMainWizard::CMainWizard(CWnd* pOwnerWnd): CCustomPropSheet(AFX_IDS_APP_TITLE, pOwnerWnd) { CUpdateItApp* pApp = DYNAMIC_DOWNCAST(CUpdateItApp, AfxGetApp()); ASSERT_VALID(pApp); // assign CRT locale static const TCHAR szDefLocale[] = _T("English_USA.1252"); _tsetlocale(LC_ALL, pApp->GetProfileString(SZ_REGK_LOCALE, SZ_REGV_LOCALE_LC_ALL, szDefLocale)); // load dialog's icons m_hIcon = pApp->LoadIcon(IDI_APP_ICON); m_hSmIcon = pApp->LoadSmIcon(MAKEINTRESOURCE(IDI_APP_ICON)); static HYPERLINKCOLORS linkColors = { RGB(0, 0, 255), // default RGB(0, 0, 255), // active RGB(0, 0, 255), // visited RGB(255, 0, 0) // hover }; CHyperLink::SetColors(linkColors); ATL::CRegKey regKeyLangs; regKeyLangs.Attach(pApp->GetSectionKey(SZ_REGK_LANGUAGES)); int nError = ERROR_SUCCESS; if (static_cast<HKEY>(regKeyLangs) != NULL) { TCHAR szLangNames[128] = { 0 }; ULONG cchNamesMax = _countof(szLangNames); nError = regKeyLangs.QueryStringValue(NULL, szLangNames, &cchNamesMax); if (nError == ERROR_SUCCESS) { LPCTSTR pszSeps = _T(",;\x20"); LPTSTR pszCurLex = _tcstok(szLangNames, pszSeps); while (pszCurLex != NULL) { m_arrLangNames.Add(pszCurLex); pszCurLex = _tcstok(NULL, pszSeps); } } ::RegCloseKey(regKeyLangs.Detach()); } g_fRestartInterface = false; AddPage(&m_pageAbout); AddPage(&m_pageFirstLaunch); AddPage(&m_pageOptions); AddPage(&m_pageFiles); AddPage(&m_pageAction); AddPage(&m_pageProgress); SetWizardMode(); }
BOOL CNTEventLogSource::Uninstall(LPCTSTR lpszLogName, LPCTSTR lpszSourceName) { //Validate our parameters ATLASSUME(lpszLogName != NULL); ATLASSERT(_tcslen(lpszLogName)); ATLASSUME(lpszSourceName != NULL); ATLASSERT(_tcslen(lpszSourceName)); //Remove the settings from the registry TCHAR szSubKey[4096]; _stprintf_s(szSubKey, sizeof(szSubKey)/sizeof(TCHAR), _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s"), lpszLogName, lpszSourceName); long nSuccess = RegDeleteKey(HKEY_LOCAL_MACHINE, szSubKey); if (nSuccess != ERROR_SUCCESS) //If we cannot delete this registry key, then abort this function before we go any further { SetLastError(nSuccess); //Make the last error value available to our callers return FALSE; } //Remove ourself from the "Sources" registry key _stprintf_s(szSubKey, sizeof(szSubKey)/sizeof(TCHAR), _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s"), lpszLogName); ATL::CRegKey appKey; if (appKey.Open(HKEY_LOCAL_MACHINE, szSubKey, KEY_WRITE | KEY_READ) == ERROR_SUCCESS) { CNTServiceStringArray sources; if (GetStringArrayFromRegistry(appKey, _T("Sources"), sources)) { //If our name is in the array then remove it BOOL bFoundMyself = FALSE; #ifdef CNTSERVICE_MFC_EXTENSIONS for (int i=0; i<sources.GetSize() && !bFoundMyself; i++) { bFoundMyself = (sources.GetAt(i) == lpszSourceName); if (bFoundMyself) { sources.RemoveAt(i); } } #else CNTServiceStringArray::iterator iterFind = std::find(sources.begin(), sources.end(), lpszSourceName); bFoundMyself = (iterFind != sources.end()); if (bFoundMyself) sources.erase(iterFind); #endif if (bFoundMyself) SetStringArrayIntoRegistry(appKey, _T("Sources"), sources); } } return TRUE; }
std::wstring RegistryHelper::readValue(const LPTSTR valueName) const { ATL::CRegKey regKey; unsigned long valSize = 0; std::wstring value; if (!( ERROR_SUCCESS == regKey.Open(key_, keyName_, KEY_READ) && ERROR_SUCCESS == regKey.QueryStringValue(valueName, NULL, &valSize) && valSize > 0 && (value.resize(valSize), ERROR_SUCCESS == regKey.QueryStringValue(valueName, (LPTSTR)value.data(), &valSize)) )) value.clear(); else value.resize(valSize - 1); return value; }
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 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 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 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 CCustomPropSheet::GetFontSubstitute(LPCTSTR pszRegvName, CString& strDest) { ATL::CRegKey regKeyFontSubst; regKeyFontSubst.Create(HKEY_LOCAL_MACHINE, SZ_REGK_FONT_SUBSTITUTES); int nError = ERROR_SUCCESS; TCHAR szMsShellDlg[LF_FACESIZE] = { 0 }; ULONG cchMaxLen = _countof(szMsShellDlg); nError = regKeyFontSubst.QueryStringValue(pszRegvName, szMsShellDlg, &cchMaxLen); if (nError == ERROR_SUCCESS) { strDest = szMsShellDlg; return (true); } else { return (false); } }
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; }
BOOL ComPortDiscovery::RegQueryValueString(ATL::CRegKey& key, LPCTSTR lpValueName, LPTSTR& pszValue) { //Initialize the output parameter pszValue = NULL; //First query for the size of the registry value ULONG nChars = 0; LSTATUS nStatus = key.QueryStringValue(lpValueName, NULL, &nChars); if (nStatus != ERROR_SUCCESS) { SetLastError(nStatus); return FALSE; } //Allocate enough bytes for the return value DWORD dwAllocatedSize = ((nChars + 1) * sizeof(TCHAR)); //+1 is to allow us to NULL terminate the data if required pszValue = reinterpret_cast<LPTSTR>(LocalAlloc(LMEM_FIXED, dwAllocatedSize)); if (pszValue == NULL) return FALSE; //We will use RegQueryValueEx directly here because ATL::CRegKey::QueryStringValue does not handle non-Null terminated data DWORD dwType = 0; ULONG nBytes = dwAllocatedSize; pszValue[0] = _T('\0'); nStatus = RegQueryValueEx(key, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(pszValue), &nBytes); if (nStatus != ERROR_SUCCESS) { LocalFree(pszValue); pszValue = NULL; SetLastError(nStatus); return FALSE; } if ((dwType != REG_SZ) && (dwType != REG_EXPAND_SZ)) { LocalFree(pszValue); pszValue = NULL; SetLastError(ERROR_INVALID_DATA); return FALSE; } if ((nBytes % sizeof(TCHAR)) != 0) { LocalFree(pszValue); pszValue = NULL; SetLastError(ERROR_INVALID_DATA); return FALSE; } if (pszValue[(nBytes / sizeof(TCHAR)) - 1] != _T('\0')) { //Forcibly NULL terminate the data ourselves pszValue[(nBytes / sizeof(TCHAR))] = _T('\0'); } return TRUE; }
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; }
bool IsPDFPrinterInstalled(std::tstring& stReason) { const _bstr_t c_sAmynuProgId = _T("CDIntfEx.CDIntfEx"); try { CLSID clsid = {0}; HRESULT hr = CLSIDFromProgID(c_sAmynuProgId, &clsid); if (S_OK != hr) throw Workshare::Com::ComException(_T("PDF converter not installed."), hr); ATL::CRegKey printerRegistry; const TCHAR c_sRegistryKey[] = _T("Software\\Microsoft\\Windows NT\\CurrentVersion\\Devices\0"); LONG lResult = printerRegistry.Open(HKEY_CURRENT_USER, c_sRegistryKey, KEY_READ); if(ERROR_SUCCESS != lResult) { CStdString sMessage; sMessage.Format(_T("Failed to open the key \"%s\" for reading the configured PDF printer"), c_sRegistryKey); throw Workshare::System::SystemException(_T("Failed to open the registry to read the configured PDF printer"), lResult); } TCHAR szData[MAX_PATH]; ULONG ulSize(sizeof(szData)/sizeof(szData[0])); lResult = printerRegistry.QueryStringValue(c_sPDFDriverName, szData, &ulSize); if(ERROR_SUCCESS != lResult) { CStdString sMessage; sMessage.Format(_T("The PDF converter is not correctly installed. The printer \"%s\" needs to be installed. Rerun the installation of the PDF printer."), c_sPDFDriverName); throw Workshare::System::SystemException(sMessage.c_str(), lResult); } } catch(const Workshare::Exception& e) { stReason = e.Message; return false; } catch(...) { unexpected(); } return true; }
void CMainWizard::OnLanguageChange(UINT uMenuID) { CUpdateItApp* pApp = DYNAMIC_DOWNCAST(CUpdateItApp, AfxGetApp()); ASSERT_VALID(pApp); ATL::CRegKey regKeyLangs; regKeyLangs.Attach(pApp->GetSectionKey(SZ_REGK_LANGUAGES)); int nError = ERROR_SUCCESS; if (static_cast<HKEY>(regKeyLangs) != NULL) { UINT iLangName = uMenuID - ((ID_LANGUAGE_ENGLISH & 0x00F0) >> 4); nError = regKeyLangs.SetStringValue(SZ_REGV_LANGUAGES_CURRENT, m_arrLangNames[iLangName]); if (nError == ERROR_SUCCESS) { CheckLangMenuItem(iLangName); regKeyLangs.Flush(); g_fRestartInterface = true; PostMessage(PSM_PRESSBUTTON, PSBTN_CANCEL, 0); } ::RegCloseKey(regKeyLangs.Detach()); }
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 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(); } }
DWORD AddinHelper::GetIntervalTime() const { TSAUTO(); DWORD dwResult = 3600; std::wstring subKey = L"Software\\"; subKey += this->m_productName; subKey += L"Host"; if (this->m_isService) { DWORD dwSessionId = ::WTSGetActiveConsoleSessionId(); HANDLE hUserToken = NULL; if(!::WTSQueryUserToken(dwSessionId, &hUserToken)) { TSERROR4CXX("WTSQueryUserToken fail. Error: " << ::GetLastError()); return dwResult; } ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseUserToken(hUserToken, ::CloseHandle); TOKEN_ELEVATION_TYPE tokenElevationType; DWORD dwSize = sizeof(TOKEN_ELEVATION_TYPE); if(!::GetTokenInformation(hUserToken, TokenElevationType, &tokenElevationType, dwSize, &dwSize)) { TSERROR4CXX("GetTokenInformation TokenElevationType fail." << ::GetLastError()); return dwResult; } HANDLE hDuplicateToken = NULL; if(tokenElevationType == TokenElevationTypeLimited) { TOKEN_LINKED_TOKEN linkedToken; dwSize = sizeof(TOKEN_LINKED_TOKEN); if (!::GetTokenInformation(hUserToken, TokenLinkedToken, &linkedToken, dwSize, &dwSize)) { TSERROR4CXX("GetTokenInformation TokenLinkedToken fail. Error: " << ::GetLastError()); return dwResult; } ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseLinkedToken(linkedToken.LinkedToken, ::CloseHandle); if(!::DuplicateTokenEx(linkedToken.LinkedToken, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &hDuplicateToken)) { TSERROR4CXX("DuplicateTokenEx fail. Error: " << ::GetLastError()); return dwResult; } } else { if(!::DuplicateTokenEx(hUserToken, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &hDuplicateToken)) { TSERROR4CXX("DuplicateTokenEx fail. Error: " << ::GetLastError()); return dwResult; } } ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseDuplicateToken(hDuplicateToken, ::CloseHandle); TCHAR szUsername[MAX_PATH]; DWORD dwUsernameLen = MAX_PATH; PROFILEINFO pi; std::memset(&pi, 0, sizeof(PROFILEINFO)); pi.dwSize = sizeof(PROFILEINFO); if(!ImpersonateLoggedOnUser(hDuplicateToken)) { TSERROR4CXX("ImpersonateLoggedOnUser failed."); return dwResult; } DWORD dwUserNameLength = MAX_PATH; if(!::GetUserName(szUsername, &dwUserNameLength)) { TSERROR4CXX("GetUserName failed."); ::RevertToSelf(); return dwResult; } ::RevertToSelf(); pi.lpUserName = szUsername; pi.dwFlags = 1; if(!::LoadUserProfile(hDuplicateToken, &pi)) { TSERROR4CXX("LoadUserProfile failed."); return dwResult; } do { ATL::CRegKey key; if (key.Open((HKEY)pi.hProfile, subKey.c_str()) != ERROR_SUCCESS) { break; } DWORD dwInterval = 0; if(key.QueryDWORDValue(L"interval", dwInterval)!= ERROR_SUCCESS) { break; } dwResult = dwInterval; } while(false); ::UnloadUserProfile(hDuplicateToken, pi.hProfile); } else { ATL::CRegKey key; TSERROR4CXX("GetIntervalTime subKey: " << subKey.c_str()); if(key.Open(HKEY_CURRENT_USER, subKey.c_str()) != ERROR_SUCCESS) { return dwResult; } DWORD dwInterval = 0; if(key.QueryDWORDValue(L"interval", dwInterval)!= ERROR_SUCCESS) { return dwResult; } dwResult = dwInterval; TSERROR4CXX("GetIntervalTime dwInterval: " << dwInterval); } if (dwResult < 600) { dwResult = 600; } return dwResult; }
BOOL CNTEventLogSource::Install(LPCTSTR lpszLogName, LPCTSTR lpszSourceName, LPCTSTR lpszEventMessageFile, LPCTSTR pszEventCategoryMessageFile, LPCTSTR pszEventParameterMessageFile, DWORD dwTypesSupported, DWORD dwCategoryCount) { //Validate our parameters ATLASSUME(lpszLogName != NULL); ATLASSERT(_tcslen(lpszLogName)); ATLASSUME(lpszSourceName != NULL); ATLASSERT(_tcslen(lpszSourceName)); ATLASSUME(lpszEventMessageFile != NULL); //What will be the return value from this function, assume the worst BOOL bSuccess = FALSE; //Make the necessary updates to the registry TCHAR szKey[4096]; _stprintf_s(szKey, sizeof(szKey)/sizeof(TCHAR), _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s"), lpszLogName); ATL::CRegKey appKey; if (appKey.Create(HKEY_LOCAL_MACHINE, szKey) == ERROR_SUCCESS) { ATL::CRegKey sourceKey; if (sourceKey.Create(appKey, lpszSourceName, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_READ, NULL) == ERROR_SUCCESS) { //Write the EventMessageFile string value bSuccess = sourceKey.SetStringValue(_T("EventMessageFile"), lpszEventMessageFile) == ERROR_SUCCESS; //Write the TypesSupported value bSuccess = bSuccess && sourceKey.SetDWORDValue(_T("TypesSupported"), dwTypesSupported) == ERROR_SUCCESS; //Write the CategoryCount value if required if (dwCategoryCount && bSuccess) bSuccess = sourceKey.SetDWORDValue(_T("CategoryCount"), dwCategoryCount) == ERROR_SUCCESS; //Write the CategoryMessageFile string if required if (pszEventCategoryMessageFile && _tcslen(pszEventCategoryMessageFile) && bSuccess) bSuccess = sourceKey.SetStringValue(_T("CategoryMessageFile"), pszEventCategoryMessageFile) == ERROR_SUCCESS; //Write the ParameterMessageFile string if required if (pszEventParameterMessageFile && _tcslen(pszEventParameterMessageFile) && bSuccess) bSuccess = sourceKey.SetStringValue(_T("ParameterMessageFile"), pszEventParameterMessageFile) == ERROR_SUCCESS; //Update the sources registry key so that the event viewer can filter on the events which we write to the event log if (bSuccess) { CNTServiceStringArray sources; if (GetStringArrayFromRegistry(appKey, _T("Sources"), sources)) { //If our name is not in the array then add it BOOL bFoundMyself = FALSE; #ifdef CNTSERVICE_MFC_EXTENSIONS for (int i=0; i<sources.GetSize() && !bFoundMyself; i++) bFoundMyself = (sources.GetAt(i) == lpszSourceName); #else bFoundMyself = (std::find(sources.begin(), sources.end(), lpszSourceName) != sources.end()); #endif if (!bFoundMyself) { #ifdef CNTSERVICE_MFC_EXTENSIONS sources.Add(lpszSourceName); #else sources.push_back(lpszSourceName); #endif SetStringArrayIntoRegistry(appKey, _T("Sources"), sources); } } } } } return bSuccess; }
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); } }
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 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); }
BOOL ComPortDiscovery::QueryUsingSetupAPI(const GUID& guid, WORD dwFlags, CPortsArray& ports, CNamesArray& friendlyNames) { //Set our output parameters to sane defaults ports.clear(); friendlyNames.clear(); //Create a "device information set" for the specified GUID HDEVINFO hDevInfoSet = SetupDiGetClassDevs(&guid, NULL, NULL, dwFlags); if (hDevInfoSet == INVALID_HANDLE_VALUE) return FALSE; //Finally do the enumeration BOOL bMoreItems = TRUE; int nIndex = 0; SP_DEVINFO_DATA devInfo; while (bMoreItems) { //Enumerate the current device devInfo.cbSize = sizeof(SP_DEVINFO_DATA); bMoreItems = SetupDiEnumDeviceInfo(hDevInfoSet, nIndex, &devInfo); if (bMoreItems) { //Did we find a serial port for this device BOOL bAdded = FALSE; //Get the registry key which stores the ports settings ATL::CRegKey deviceKey; deviceKey.Attach(SetupDiOpenDevRegKey(hDevInfoSet, &devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE)); if (deviceKey != INVALID_HANDLE_VALUE) { int nPort = 0; if (QueryRegistryPortName(deviceKey, nPort)) { ports.push_back(nPort); bAdded = TRUE; } } //If the port was a serial port, then also try to get its friendly name if (bAdded) { ATL::CHeapPtr<BYTE> byFriendlyName; if (QueryDeviceDescription(hDevInfoSet, devInfo, byFriendlyName)) { friendlyNames.push_back(reinterpret_cast<LPCTSTR>(byFriendlyName.m_pData)); } else { friendlyNames.push_back(_T("")); } } } ++nIndex; } //Free up the "device information set" now that we are finished with it SetupDiDestroyDeviceInfoList(hDevInfoSet); //Return the success indicator return TRUE; }
BOOL CNTEventLogSource::GetStringArrayFromRegistry(ATL::CRegKey& key, LPCTSTR lpszEntry, CNTServiceStringArray& array, DWORD* pLastError) { //Validate our parameters ATLASSERT(lpszEntry != NULL); //What will be the return value from this function, assume the worst BOOL bSuccess = FALSE; //Empty the array before we go any further #ifdef CNTSERVICE_MFC_EXTENSIONS array.RemoveAll(); #else array.clear(); #endif DWORD dwType = 0; ULONG nBytes = 0; LONG lResult = key.QueryValue(lpszEntry, &dwType, NULL, &nBytes); if (lResult == ERROR_SUCCESS) { //Allocate some memory for the API ATL::CHeapPtr<TCHAR> lpBuffer; ULONG nChars = nBytes / sizeof(TCHAR); if (nChars < 2) //Ensure we can handle an empty MULTI_SZ string nChars = 2; if (!lpBuffer.Allocate(nChars)) { SetLastError(ERROR_OUTOFMEMORY); if (pLastError) *pLastError = ERROR_OUTOFMEMORY; return FALSE; } lResult = key.QueryMultiStringValue(lpszEntry, lpBuffer, &nChars); if (lResult == ERROR_SUCCESS) { LPTSTR lpszStrings = lpBuffer.m_pData; while (lpszStrings[0] != 0) { #ifdef CNTSERVICE_MFC_EXTENSIONS array.Add(lpszStrings); #else array.push_back(lpszStrings); #endif lpszStrings += (_tcslen(lpszStrings) + 1); } bSuccess = TRUE; } else { if (pLastError) *pLastError = lResult; } } else { if (pLastError) *pLastError = lResult; } return bSuccess; }
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; }
BOOL CNTEventLogSource::SetStringArrayIntoRegistry(ATL::CRegKey& key, LPCTSTR lpszEntry, const CNTServiceStringArray& array, DWORD* pLastError) { //Validate our input parameters ATLASSERT(lpszEntry != NULL); //Work out the size of the buffer we will need #ifdef CNTSERVICE_MFC_EXTENSIONS int nSize = 0; INT_PTR nStrings = array.GetSize(); for (INT_PTR i=0; i<nStrings; i++) nSize += array.GetAt(i).GetLength() + 1; //1 extra for each NULL terminator #else CNTServiceStringArray::size_type nSize = 0; CNTServiceStringArray::size_type nStrings = array.size(); for (CNTServiceStringArray::size_type i=0; i<nStrings; i++) nSize += array[i].length() + 1; //1 extra for each NULL terminator #endif //Need one second NULL for the double NULL at the end nSize++; //Allocate some memory for the API ATL::CHeapPtr<TCHAR> lpBuffer; if (!lpBuffer.Allocate(nSize)) { SetLastError(ERROR_OUTOFMEMORY); if (pLastError) *pLastError = ERROR_OUTOFMEMORY; return FALSE; } //Now copy the strings into the buffer LPTSTR lpszString = lpBuffer.m_pData; #ifdef CNTSERVICE_MFC_EXTENSIONS int nCurOffset = 0; for (INT_PTR i=0; i<nStrings; i++) #else CNTServiceStringArray::size_type nCurOffset = 0; for (CNTServiceStringArray::size_type i=0; i<nStrings; i++) #endif { const CNTServiceString& sText = array[i]; #ifdef CNTSERVICE_MFC_EXTENSIONS int nCurrentStringLength = sText.GetLength(); _tcscpy_s(&lpszString[nCurOffset], nCurrentStringLength+1, sText); #else CNTServiceString::size_type nCurrentStringLength = sText.length(); _tcscpy_s(&lpszString[nCurOffset], nCurrentStringLength+1, sText.c_str()); #endif nCurOffset += (nCurrentStringLength + 1); } //Don't forgot to doubly NULL terminate lpszString[nCurOffset] = _T('\0'); //Finally write it into the registry LONG lResult = key.SetMultiStringValue(lpszEntry, lpBuffer); BOOL bSuccess = (lResult == ERROR_SUCCESS); if (!bSuccess && pLastError) *pLastError = lResult; return bSuccess; }