void xrMemory::mem_compact () { RegFlushKey ( HKEY_CLASSES_ROOT ); RegFlushKey ( HKEY_CURRENT_USER ); if (g_allow_heap_min) _heapmin ( ); HeapCompact (GetProcessHeap(),0); if (g_pStringContainer) g_pStringContainer->clean (); if (g_pSharedMemoryContainer) g_pSharedMemoryContainer->clean (); if (strstr(Core.Params,"-swap_on_compact")) SetProcessWorkingSetSize (GetCurrentProcess(),size_t(-1),size_t(-1)); }
static BOOL create_new_eventlog(void) { HKEY key, eventkey; BOOL bret = FALSE; LONG lret; DWORD i; /* First create our eventlog */ lret = RegOpenKeyA(HKEY_LOCAL_MACHINE, eventlogsvc, &key); if (lret != ERROR_SUCCESS) { skip("Could not open the EventLog service registry key\n"); return FALSE; } lret = RegCreateKeyA(key, eventlogname, &eventkey); if (lret != ERROR_SUCCESS) { skip("Could not create the eventlog '%s' registry key\n", eventlogname); goto cleanup; } /* Create some event sources, the registry value 'Sources' is updated automatically */ for (i = 0; i < sizeof(eventsources)/sizeof(eventsources[0]); i++) { HKEY srckey; lret = RegCreateKeyA(eventkey, eventsources[i], &srckey); if (lret != ERROR_SUCCESS) { skip("Could not create the eventsource '%s' registry key\n", eventsources[i]); goto cleanup; } RegFlushKey(srckey); RegCloseKey(srckey); } bret = TRUE; /* The flushing of the registry (here and above) gives us some assurance * that we are not to quickly writing events as 'Sources' could still be * not updated. */ RegFlushKey(eventkey); cleanup: RegCloseKey(eventkey); RegCloseKey(key); return bret; }
/** * Sets the specified value in the given key, returning TRUE for * success and FALSE for failure (errors are not expected in * this function and indicate some unknown problem with registry * interaction). The flush parameter indicates that we should force * the registry to record this value after setting it (as opposed * to allowing the registry to write the value lazily). */ BOOL RegistryKey::SetIntValue(WCHAR *valueName, int regValue, BOOL flush) { if (disableRegistry) { return TRUE; } if (!hKey) { PrintRegistryError(0, "Null hKey in SetIntValue"); return FALSE; } DWORD valueLength = 4; DWORD ret = RegSetValueEx(hKey, valueName, 0, REG_DWORD, (LPBYTE)®Value, valueLength); if (ret != ERROR_SUCCESS) { PrintRegistryError(ret, "RegSetValueEx"); return FALSE; } if (flush) { ret = RegFlushKey(hKey); if (ret != ERROR_SUCCESS) { PrintRegistryError(ret, "RegFlushKey"); return FALSE; } } return TRUE; }
BOOL My_RegFlushKey() { HKEY hKey=NULL; LONG returnVal_Real = NULL; LONG returnVal_Intercepted = NULL; DWORD error_Real = 0; DWORD error_Intercepted = 0; disableInterception(); returnVal_Real = RegFlushKey (hKey); error_Real = GetLastError(); enableInterception(); returnVal_Intercepted = RegFlushKey (hKey); error_Intercepted = GetLastError(); return ((returnVal_Real == returnVal_Intercepted) && (error_Real == error_Intercepted)); }
bool spoutDirectX::WriteDwordToRegistry(DWORD dwValue, const char *subkey, const char *valuename) { HKEY hRegKey; LONG regres; char mySubKey[512]; // The required key strcpy_s(mySubKey, 512, subkey); // Does the key already exist ? regres = RegOpenKeyExA(HKEY_CURRENT_USER, mySubKey, NULL, KEY_ALL_ACCESS, &hRegKey); if(regres != ERROR_SUCCESS) { // Create a new key regres = RegCreateKeyExA(HKEY_CURRENT_USER, mySubKey, NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,NULL, &hRegKey, NULL); } if(regres == ERROR_SUCCESS && hRegKey != NULL) { // Write the DWORD value regres = RegSetValueExA(hRegKey, valuename, 0, REG_DWORD, (BYTE*)&dwValue, 4); // For immediate read after write - necessary here because the app might set the values // and read the registry straight away and it might not be available yet // The key must have been opened with the KEY_QUERY_VALUE access right (included in KEY_ALL_ACCESS) RegFlushKey(hRegKey); // needs an open key RegCloseKey(hRegKey); // Done with the key } if(regres == ERROR_SUCCESS) return true; else return false; }
/*-------------------------------------------------------------------------- Save the current autoplay setting, then disable autoplay. --------------------------------------------------------------------------*/ void tracklen_AutoPlay_Disable() { int res; HKEY hkey; /* Look for AutoPlay registry key. * Get its current value into oldAutoRunValue. * Set its value to disable autorun from any medium type. */ hkey = NULL; res = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer", 0, KEY_ALL_ACCESS, &hkey); if (res == ERROR_SUCCESS) { // The autorun key exists. // If this is the first call, get the autorun key's value. // Otherwise, just keep the value from the first call. // This guards against multiple calls. if (s_oldAutoRunValue == AUTORUN_UNKNOWN) { unsigned long ulDataSize = sizeof(s_oldAutoRunValue); res = RegQueryValueEx(hkey, "NoDriveTypeAutoRun", 0, NULL, (unsigned char*)&s_oldAutoRunValue, &ulDataSize); } // Now set its value to DISABLED. if (res == ERROR_SUCCESS) { unsigned long ulDisableAutoRun = AUTORUN_DISABLE; RegSetValueEx(hkey, "NoDriveTypeAutoRun", 0, REG_BINARY, (const unsigned char*)&ulDisableAutoRun, 4); } RegFlushKey(hkey); RegCloseKey(hkey); } }
codeUNINSTALL_INIT Uninstall_Init( HWND hwndParent, LPCTSTR pszInstallDir ) { // Disable Today Plugin HKEY key; DWORD dwEnabled, dwRet; DWORD lpcbData = sizeof(dwEnabled); dwRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("\\Software\\Microsoft\\Today\\Items\\PockeTwit"),0,0,&key); dwEnabled = 0; dwRet = RegSetValueEx(key,_T("Enabled"),0,REG_DWORD,(LPBYTE)&dwEnabled,sizeof(DWORD)); RegFlushKey(key); RegCloseKey(key); PostMessage(HWND_BROADCAST, WM_WININICHANGE, 0xF2, 0); Sleep(1000); return codeUNINSTALL_INIT_CONTINUE; }
static boolean winregdeletekey (HKEY hkey, Handle h) { /* 7.0.2b1 Radio PBS: delete a key. */ long lentext; boolean fl = true; lentext = gethandlesize (h); sethandlesize (h, lentext + 1); (*h) [lentext] = '\0'; /*null terminate*/ lockhandle (h); if (RegOpenKeyEx (hkey, *h, 0, KEY_SET_VALUE, &hkey) == ERROR_SUCCESS) { if (RegDeleteKey (hkey, *h) == ERROR_SUCCESS) { fl = true; RegFlushKey (hkey); } /*if*/ RegCloseKey (hkey); } /*if*/ unlockhandle (h); return (fl); } /*winregdeletekey*/
BOOL CreateUserHive (LPCWSTR lpKeyName, LPCWSTR lpProfilePath) { HKEY hDefaultKey = NULL; HKEY hUserKey = NULL; LONG Error; BOOL Ret = FALSE; DPRINT ("CreateUserHive(%S) called\n", lpKeyName); Error = RegOpenKeyExW (HKEY_USERS, L".Default", 0, KEY_READ, &hDefaultKey); if (Error != ERROR_SUCCESS) { SetLastError((DWORD)Error); goto Cleanup; } Error = RegOpenKeyExW (HKEY_USERS, lpKeyName, 0, KEY_ALL_ACCESS, &hUserKey); if (Error != ERROR_SUCCESS) { SetLastError((DWORD)Error); goto Cleanup; } if (!CopyKey(hUserKey, hDefaultKey)) { goto Cleanup; } if (!UpdateUsersShellFolderSettings(lpProfilePath, hUserKey)) { goto Cleanup; } RegFlushKey (hUserKey); Ret = TRUE; Cleanup: if (hUserKey != NULL) RegCloseKey (hUserKey); if (hDefaultKey != NULL) RegCloseKey (hDefaultKey); return Ret; }
void prefs_close (void *node) { HKEY hk; hk=(HKEY) node; RegFlushKey(hk); RegCloseKey(hk); }
BOOL CRegistry::Flush() { ASSERT(m_hKey); long lReturn = RegFlushKey(m_hKey); if (lReturn == ERROR_SUCCESS) return TRUE; return FALSE; }
/* * Sets a property value. * * @param property - the property name * @param value - the property value (zero terminated string) */ void DeviceManagementNode::setPropertyValue(const char* prop, const char* value) { if ((prop == NULL) || (value == NULL)) { return; } HKEY key; DWORD res; TCHAR *p = NULL; TCHAR *v = NULL; RegCreateKeyEx( HKEY_DM_ROOT, fullContext, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &res ); if (key == 0) { //lastErrorCode = ERR_INVALID_CONTEXT; //sprintf(lastErrorMsg, "Invalid context path: %s", fullContext); setErrorF(ERR_INVALID_CONTEXT, "Invalid context path: %s", fullContext); goto finally; } p = toWideChar(prop); v = toWideChar(value); RegSetValueEx( key, p, NULL, REG_SZ, // we currently support only strings (UCHAR*)v, (wcslen(v)+1)*sizeof(WCHAR) ); delete [] p; delete [] v; RegFlushKey(key); finally: if (key != 0) { RegCloseKey(key); } }
// Flushes the active key ( Write to hard disk ) bool RegKey::Flush() { if (hTheKey_ == NULL) return true; if (RegFlushKey(hTheKey_) != ERROR_SUCCESS) { iLastErrorCode_ = GetLastError(); return false; } iLastErrorCode_ = ERROR_SUCCESS; return true; }
/** * SetService **/ STDAPI SetService(LPWSTR ServiceProvider) { HKEY hKey = NULL; HRESULT hr = E_FAIL; hr = RegOpenKeyEx(HKEY_CLASSES_ROOT, _TEXT_CLSIDKEY, 0, 0, &hKey); if (hr == ERROR_SUCCESS) { RegSetValueExW(hKey, TEXT("Service Provider"), 0, REG_SZ, (LPBYTE)ServiceProvider, wcslen(ServiceProvider) * sizeof(WCHAR)); RegCloseKey(hKey); RegFlushKey(HKEY_CLASSES_ROOT); } return hr; }
BOOLEAN CTestPage::SavePCIConfiguration( BYTE ucBusNumber, BYTE ucDevice ) ///////////////////////////////////////////////////////////////////////////// { #ifdef USEHARDWARE HKEY hKey; DWORD dwDisposition; ULONG ulValue; BYTE ucDeviceFunction; int i; char szBuffer[ 128 ]; sprintf( szBuffer, REG_STR_PATH, ucBusNumber, ucDevice ); ucDeviceFunction = ucDevice << 3; RegCreateKeyEx( HKEY_CURRENT_USER, szBuffer, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition ); ReadConfigurationArea( READ_CONFIG_BYTE, ucBusNumber, ucDeviceFunction, PCI_CS_CACHE_LINE_SIZE, &ulValue ); ulValue &= 0xFF; RegSetValueEx( hKey, "CacheLineSize", 0, REG_DWORD, (LPBYTE)&ulValue, sizeof( ULONG ) ); ReadConfigurationArea( READ_CONFIG_BYTE, ucBusNumber, ucDeviceFunction, PCI_CS_MASTER_LATENCY, &ulValue ); ulValue &= 0xFF; RegSetValueEx( hKey, "MasterLatency", 0, REG_DWORD, (LPBYTE)&ulValue, sizeof( ULONG ) ); for( i=0; i<PCI_TYPE0_ADDRESSES; i++ ) { ReadConfigurationArea( READ_CONFIG_DWORD, ucBusNumber, ucDeviceFunction, PCI_CS_BASE_ADDRESS_0+(i*sizeof(ULONG)), &ulValue ); sprintf( szBuffer, "BAR%d", i ); RegSetValueEx( hKey, szBuffer, 0, REG_DWORD, (LPBYTE)&ulValue, sizeof( ULONG ) ); } ReadConfigurationArea( READ_CONFIG_BYTE, ucBusNumber, ucDeviceFunction, PCI_CS_INTERRUPT_LINE, &ulValue ); ulValue &= 0xFF; RegSetValueEx( hKey, "InterruptLine", 0, REG_DWORD, (LPBYTE)&ulValue, sizeof( ULONG ) ); RegFlushKey( hKey ); RegCloseKey( hKey ); #endif return( TRUE ); }
/*-------------------------------------------------------------------------- Restore the autoplay setting saved by AutoPlay_Disable(). --------------------------------------------------------------------------*/ void tracklen_AutoPlay_Restore() { int res; HKEY hkey = NULL; // If AutoPlay_Disable() was never called, just return. if (s_oldAutoRunValue == AUTORUN_UNKNOWN) { return; } // Restore AutoPlay setting res = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer", 0, KEY_ALL_ACCESS, &hkey); if (res == ERROR_SUCCESS) { RegSetValueEx(hkey, "NoDriveTypeAutoRun", 0, REG_BINARY, (const unsigned char*)&s_oldAutoRunValue, 4); RegFlushKey(hkey); RegCloseKey(hkey); } }
/** * General function for changing registry entries, creates if they dont already exist * * @param const char *reg_path - Path of key * @param const char *keyname - Name of subkey * @param int reg_type - HKEY_CLASSES_ROOT, HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS * @param void *data - Pointer to the data * @param int data_len - Length of data in buffer * * @return bool - states if value set happened OK */ bool reg_set_value(const char *reg_path, const char *keyname, int reg_type, void *data, int data_len) { // Try to open the correct registry dir HKEY hkey = reg_open_dir(reg_path); if(hkey == NULL) { return false; } if(RegSetValueEx(hkey, keyname, 0, reg_type, (BYTE *) data, data_len) != ERROR_SUCCESS) { RegCloseKey(hkey); return false; } RegFlushKey(hkey); RegCloseKey(hkey); return true; }
HX_RESULT CWinRegKey::Flush() { if(!m_bOpen) { return HXR_UNEXPECTED; } if ( RegFlushKey(m_hkThis) == ERROR_SUCCESS ) { return HXR_OK; } return HXR_FAIL; }
int dc_save_conf(dc_conf_data *conf) { dc_conf d_conf; HKEY h_key = NULL; u32 build = DC_DRIVER_VER; int resl; do { if (RegCreateKey(HKEY_LOCAL_MACHINE, reg_srv, &h_key) != 0) { resl = ST_REG_ERROR; break; } if (RegSetValueEx(h_key, L"Flags", 0, REG_DWORD, pv(&conf->conf_flags), sizeof(conf->conf_flags)) != 0) { resl = ST_REG_ERROR; break; } if (RegSetValueEx(h_key, L"Hotkeys", 0, REG_BINARY, pv(&conf->hotkeys), sizeof(conf->hotkeys)) != 0) { resl = ST_REG_ERROR; break; } if (RegSetValueEx(h_key, L"sysBuild", 0, REG_DWORD, pv(&build), sizeof(build)) != 0) { resl = ST_REG_ERROR; break; } RegFlushKey(h_key); d_conf.conf_flags = conf->conf_flags; d_conf.load_flags = conf->load_flags; dc_set_conf_flags(&d_conf); resl = ST_OK; } while (0); if (h_key != NULL) { RegCloseKey(h_key); } return resl; }
USER_OBJECT_ R_deleteRegKey(USER_OBJECT_ hkey, USER_OBJECT_ path, USER_OBJECT_ subKey, USER_OBJECT_ asKey, USER_OBJECT_ recursive) { USER_OBJECT_ ans; HKEY lkey; char *tmp; LONG status = ERROR_SUCCESS; lkey = getOpenRegKey(hkey, path); tmp = CHAR_DEREF(STRING_ELT(subKey, 0)); if(!tmp[0]) tmp = NULL; if(LOGICAL_DATA(asKey)[0]) { status = RegDeleteKey(lkey, tmp); } else status = RegDeleteValue(lkey, tmp); if(status != ERROR_SUCCESS) { char errBuf[1000]; RegCloseKey(lkey); FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errBuf, sizeof(errBuf)/sizeof(errBuf[0]), NULL); PROBLEM "Error deleting %s (%s): (%d) %s ", (LOGICAL_DATA(asKey)[0] ? "key" : "value"), (tmp ? tmp : ""), (int) status, errBuf ERROR; } RegFlushKey(lkey); RegCloseKey(lkey); ans = NEW_LOGICAL(1); LOGICAL_DATA(ans)[0] = TRUE; return(ans); }
USER_OBJECT_ R_flushRegKey(USER_OBJECT_ hkey, USER_OBJECT_ path, USER_OBJECT_ subKey) { USER_OBJECT_ ans; HKEY lkey; DWORD status; lkey = getOpenRegKey(hkey, path); status = RegFlushKey(lkey); if(status != ERROR_SUCCESS) { char errBuf[1000]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errBuf, sizeof(errBuf)/sizeof(errBuf[0]), NULL); PROBLEM "Error flushing key: %s", errBuf ERROR; } ans = NEW_LOGICAL(1); LOGICAL_DATA(ans)[0] = TRUE; return(ans); }
static void flush_this_key(HKEY parent, const char *name) { HKEY key; DWORD err; err = RegOpenKeyEx(parent, name, 0, KEY_QUERY_VALUE, &key); if (err != ERROR_SUCCESS) { /* For some reason which remains obscure to me, a default XP installation doesn't give Administrator sufficient access rights to flush all keys to disk. It does give them sufficient access rights to grant themselves access to flush all keys, or to create a service which has permission to flush keys on their behalf, but that doesn't really sound like something I'd want to do. Deal with it by just ignoring security errors on the affected key. It's not one which we ever need to modify, anyway, and if Windows is modifying it behind our back and forgetting to flush then we're already screwed. */ if (err == ERROR_ACCESS_DENIED && parent == HKEY_LOCAL_MACHINE && !strcmp(name, "SECURITY")) return; SetLastError(err); xs_win_err(1, &xs_render_error_msgbox, "cannot open registry key %s to synchronise it to disk", name); } err = RegFlushKey(key); if (err != ERROR_SUCCESS) { SetLastError(err); xs_win_err(1, &xs_render_error_msgbox, "cannot synchronise registry key %s to disk", name); } RegCloseKey(key); }
USER_OBJECT_ R_createRegistryKey(USER_OBJECT_ hkey, USER_OBJECT_ subKey) { HKEY lkey, key; DWORD created; USER_OBJECT_ ans; char *name; LONG status = ERROR_SUCCESS; lkey = getOpenRegKey(hkey, subKey); name = CHAR_DEREF(STRING_ELT(subKey, 1)); status = RegCreateKeyEx(lkey, name, 0, (char *) NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &created); if(status != ERROR_SUCCESS) { char errBuf[1000]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errBuf, sizeof(errBuf)/sizeof(errBuf[0]), NULL); RegCloseKey(lkey); PROBLEM "Can't create key %s: %s", name, errBuf ERROR; } ans = NEW_LOGICAL(1); if(created == REG_OPENED_EXISTING_KEY ) { RegCloseKey(key); } else { RegFlushKey(key); LOGICAL_DATA(ans)[0] = TRUE; } RegCloseKey(lkey); return(ans); }
JNIEXPORT jint JNICALL Java_java_util_prefs_WindowsPreferences_WindowsRegFlushKey (JNIEnv* env, jclass this_class, jint hKey) { return RegFlushKey ((HKEY)hKey); }
JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegFlushKey) (JNIEnv *env, jclass, long hkey) { return RegFlushKey((HKEY)hkey); }
static BOOL ImportRegistryFile(HWND hWnd) { BOOL bRet = FALSE; OPENFILENAME ofn; WCHAR Caption[128], szTitle[512], szText[512]; HKEY hKeyRoot; LPCWSTR pszKeyPath; /* Figure out in which key path we are importing */ pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot); InitOpenFileName(hWnd, &ofn); LoadStringW(hInst, IDS_IMPORT_REG_FILE, Caption, COUNT_OF(Caption)); ofn.lpstrTitle = Caption; ofn.Flags |= OFN_ENABLESIZING; /* ofn.lCustData = ;*/ if (GetOpenFileName(&ofn)) { /* Look at the extension of the file to determine its type */ if (ofn.nFileExtension >= 1 && _wcsicmp(ofn.lpstrFile + ofn.nFileExtension, L"reg") == 0) /* REGEDIT4 or Windows Registry Editor Version 5.00 */ { /* Open the file */ FILE* fp = _wfopen(ofn.lpstrFile, L"r"); /* Import it */ if (fp == NULL || !import_registry_file(fp)) { /* Error opening the file */ LoadStringW(hInst, IDS_APP_TITLE, szTitle, COUNT_OF(szTitle)); LoadStringW(hInst, IDS_IMPORT_ERROR, szText, COUNT_OF(szText)); InfoMessageBox(hWnd, MB_OK | MB_ICONERROR, szTitle, szText, ofn.lpstrFile); bRet = FALSE; } else { /* Show successful import */ LoadStringW(hInst, IDS_APP_TITLE, szTitle, COUNT_OF(szTitle)); LoadStringW(hInst, IDS_IMPORT_OK, szText, COUNT_OF(szText)); InfoMessageBox(hWnd, MB_OK | MB_ICONINFORMATION, szTitle, szText, ofn.lpstrFile); bRet = TRUE; } /* Close the file */ if (fp) fclose(fp); } else /* Registry Hive Files */ { LoadStringW(hInst, IDS_QUERY_IMPORT_HIVE_CAPTION, szTitle, COUNT_OF(szTitle)); LoadStringW(hInst, IDS_QUERY_IMPORT_HIVE_MSG, szText, COUNT_OF(szText)); /* Display a confirmation message */ if (MessageBoxW(g_pChildWnd->hWnd, szText, szTitle, MB_ICONWARNING | MB_YESNO) == IDYES) { LONG lResult; HKEY hSubKey; /* Open the subkey */ lResult = RegOpenKeyExW(hKeyRoot, pszKeyPath, 0, KEY_WRITE, &hSubKey); if (lResult == ERROR_SUCCESS) { /* Enable the 'restore' privilege, restore the hive then disable the privilege */ EnablePrivilege(SE_RESTORE_NAME, NULL, TRUE); lResult = RegRestoreKey(hSubKey, ofn.lpstrFile, REG_FORCE_RESTORE); EnablePrivilege(SE_RESTORE_NAME, NULL, FALSE); /* Flush the subkey and close it */ RegFlushKey(hSubKey); RegCloseKey(hSubKey); } /* Set the return value */ bRet = (lResult == ERROR_SUCCESS); /* Display error, if any */ if (!bRet) ErrorMessageBox(hWnd, Caption, lResult); } } } else { CheckCommDlgError(hWnd); } /* refresh tree and list views */ RefreshTreeView(g_pChildWnd->hTreeWnd); pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hKeyRoot); RefreshListView(g_pChildWnd->hListWnd, hKeyRoot, pszKeyPath); return bRet; }
BOOL CUac::Set( __in UAC_LEVEL UacLevel ) { BOOL bRet = FALSE; HKEY hKey = NULL; LONG lResult = 0; DWORD dwConsentPromptBehaviorAdmin = 0; DWORD dwEnableLUA = 0; DWORD dwPromptOnSecureDesktop = 0; __try { lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"), 0, KEY_ALL_ACCESS, &hKey ); if (ERROR_SUCCESS != lResult) { printfPublic("RegOpenKeyEx failed. (%d)", lResult); __leave; } switch (UacLevel) { case UAC_LEVEL_1: { // 2 1 1 dwConsentPromptBehaviorAdmin = 2; dwEnableLUA = 1; dwPromptOnSecureDesktop = 1; break; } case UAC_LEVEL_2: { // 5 1 1 dwConsentPromptBehaviorAdmin = 5; dwEnableLUA = 1; dwPromptOnSecureDesktop = 1; break; } case UAC_LEVEL_3: { // 5 1 0 dwConsentPromptBehaviorAdmin = 5; dwEnableLUA = 1; dwPromptOnSecureDesktop = 0; break; } case UAC_LEVEL_4: { // 0 0 0 dwConsentPromptBehaviorAdmin = 0; dwEnableLUA = 0; dwPromptOnSecureDesktop = 0; break; } default: { printfPublic("UacLevel error. (%d)", UacLevel); __leave; } } lResult = RegSetValueEx( hKey, _T("ConsentPromptBehaviorAdmin"), NULL, REG_DWORD, (const BYTE*)&dwConsentPromptBehaviorAdmin, sizeof(DWORD) ); if (ERROR_SUCCESS != lResult) { printfPublic("RegSetValueEx failed. ConsentPromptBehaviorAdmin (%d)", lResult); __leave; } if (!hKey) { printfPublic("hKey error"); __leave; } lResult = RegSetValueEx( hKey, _T("EnableLUA"), NULL, REG_DWORD, (const BYTE*)&dwEnableLUA, sizeof(DWORD) ); if (ERROR_SUCCESS != lResult) { printfPublic("RegSetValueEx failed. EnableLUA (%d)", lResult); __leave; } lResult = RegSetValueEx( hKey, _T("PromptOnSecureDesktop"), NULL, REG_DWORD, (const BYTE*)&dwPromptOnSecureDesktop, sizeof(DWORD) ); if (ERROR_SUCCESS != lResult) { printfPublic("RegSetValueEx failed. PromptOnSecureDesktop (%d)", lResult); __leave; } bRet = TRUE; } __finally { if (hKey) { if (bRet) RegFlushKey(hKey); RegCloseKey(hKey); hKey = NULL; } } return bRet; }
BOOL InstallService(const char* pFullExePath, const char* pServiceName, const char* pServiceParams, const char* pLogonName, const char* pLogonPassword) { BOOL fReturnCode = FALSE; LONG lRet = 0; HKEY hkEvent = NULL; HKEY hkService = NULL; HKEY hkObject = NULL; DWORD dwDisposition = 0; DWORD dwData = 0; SC_HANDLE schSCManager = NULL; SC_HANDLE schService = NULL; CHAR pExePath[MAX_DISPLAY_NAME] = {0}; CHAR pServiceLogon[MAX_DISPLAY_NAME] = {0}; CHAR pServiceKey[MAX_DISPLAY_NAME] = {0}; SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sdPermissions; // If an exe path was passed in, use it if (pFullExePath) { strcpy(pExePath, pFullExePath); } // Otherwise use the path for the current module else { GetModuleFileName(NULL, (LPTSTR)pExePath, MAX_DISPLAY_NAME); } sprintf(pServiceLogon, ".\\%s", (pLogonName ? pLogonName : "")); // Connect to the local SCM schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (schSCManager == NULL) { fReturnCode = FALSE; goto cleanup; } // Create the service if (!pLogonName || !*pLogonName || !pLogonPassword) { schService = CreateService( schSCManager, pServiceName, pServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, pExePath, NULL, NULL, NULL, NULL, NULL); } else { schService = CreateService( schSCManager, pServiceName, pServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, pExePath, NULL, NULL, NULL, (LPCTSTR)(pServiceLogon), (LPCTSTR)(pLogonPassword)); } if (schService == NULL) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); // Display the string fprintf(stderr, "%s\n", lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); fReturnCode = FALSE; goto cleanup; } // Generate security attribute/descriptor for the specified user if (pLogonName && *pLogonName) { // SD if (!CreateSecurityDescriptor(pLogonName, &sdPermissions)) { fReturnCode = FALSE; goto cleanup; } // SA sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = &sdPermissions; } // Create the event log entry lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, REGISTRY_KEY_EVENTLOG, 0, KEY_ALL_ACCESS, &hkEvent); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } // Create event key lRet = CREATEKEY(hkEvent, pServiceName, hkObject, dwDisposition); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } // Set the value lRet = SETSZVALUE(hkObject, "EventMessageFile", pExePath); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; lRet = SETDWVALUE(hkObject, "TypesSupported", &dwData); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } // Open the service registry key sprintf(pServiceKey, "%s\\%s", REGISTRY_KEY_SERVICE, pServiceName); lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE, pServiceKey, 0, KEY_ALL_ACCESS, &hkService); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } if (pLogonName && *pLogonName) { // Set the security lRet = RegSetKeySecurity( hkService, (SECURITY_INFORMATION)(DACL_SECURITY_INFORMATION), &sdPermissions); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } } // Create StartupParams value if (pServiceParams) { lRet = SETSZVALUE(hkService, "StartupParams", pServiceParams); if (lRet != ERROR_SUCCESS) { fReturnCode = FALSE; goto cleanup; } } fReturnCode = TRUE; cleanup: FREEHSCM(schService); FREEHSCM(schSCManager); FREEHKEY(hkEvent); FREEHKEY(hkService); FREEHKEY(hkObject); RegFlushKey(HKEY_LOCAL_MACHINE); return fReturnCode; }
void QWinSettingsPrivate::sync() { RegFlushKey(writeHandle()); }
BOOLEAN ScmDrvCtrl::Install(const TCHAR* lpszServiceName, const TCHAR* lpszDriverPath, const TCHAR* lpszAltitude, const TCHAR* lpszLink_name) { SC_HANDLE hServiceMgr = NULL; SC_HANDLE hService = NULL; int i = 0; _tcscpy_s(m_link_name, MAX_PATH, lpszLink_name); if (NULL == lpszServiceName || NULL == lpszDriverPath || NULL == lpszAltitude) { return FALSE; } UnInstall(lpszServiceName); WIN32_FIND_DATA FindFileData; if (FindFirstFileW(lpszDriverPath, &FindFileData) == INVALID_HANDLE_VALUE) { return FALSE; } again: hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hServiceMgr == NULL) { return FALSE; } hService = CreateService(hServiceMgr, lpszServiceName, // 驱动程序的在注册表中的名字 lpszServiceName, // 注册表驱动程序的DisplayName 值 SERVICE_ALL_ACCESS, // 加载驱动程序的访问权限 SERVICE_FILE_SYSTEM_DRIVER, // 表示加载的服务是文件系统驱动程序 SERVICE_DEMAND_START, // 注册表驱动程序的Start 值 SERVICE_ERROR_IGNORE, // 注册表驱动程序的ErrorControl 值 lpszDriverPath, // 注册表驱动程序的ImagePath 值 _T("FSFilter Activity Monitor"),// 注册表驱动程序的Group 值 NULL, _T("FltMgr"), // 注册表驱动程序的DependOnService 值 NULL, NULL); if (hService == NULL) { CloseServiceHandle(hServiceMgr); if (i > 100000) { return FALSE; } i++; // printf("%d\n", i); goto again; } CloseServiceHandle(hService); // 服务句柄 CloseServiceHandle(hServiceMgr); // SCM句柄 TCHAR szTempStr[MAX_PATH]; HKEY hKey = NULL; DWORD dwData = 0; _tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\")); _tcscat_s(szTempStr, MAX_PATH, lpszServiceName); if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS) { return FALSE; } _tcscpy_s(szTempStr, MAX_PATH, lpszServiceName); if (RegSetValueEx(hKey, _T("service_name"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS) { return FALSE; } //GetWindowsDirectory(szTempStr,MAX_PATH); //if (RegSetValueEx(hKey, _T("system_dir"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS) //{ // return FALSE; //} RegFlushKey(hKey); RegCloseKey(hKey); _tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\")); _tcscat_s(szTempStr, MAX_PATH, lpszServiceName); _tcscat_s(szTempStr, MAX_PATH, _T("\\Instances")); if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS) { return FALSE; } _tcscpy_s(szTempStr, MAX_PATH, lpszServiceName); _tcscat_s(szTempStr, MAX_PATH, _T(" Instance")); if (RegSetValueEx(hKey, _T("DefaultInstance"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS) { return FALSE; } RegFlushKey(hKey); RegCloseKey(hKey); _tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\")); _tcscat_s(szTempStr, MAX_PATH, lpszServiceName); _tcscat_s(szTempStr, MAX_PATH, _T("\\Instances\\")); _tcscat_s(szTempStr, MAX_PATH, lpszServiceName); _tcscat_s(szTempStr, MAX_PATH, _T(" Instance")); if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS) { return FALSE; } _tcscpy_s(szTempStr, lpszAltitude); if (RegSetValueEx(hKey, _T("Altitude"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS) { return FALSE; } dwData = 0x0; if (RegSetValueEx(hKey, _T("Flags"), 0, REG_DWORD, (CONST BYTE*)&dwData, sizeof(DWORD)) != ERROR_SUCCESS) { return FALSE; } RegFlushKey(hKey); RegCloseKey(hKey); return TRUE; }