簡體   English   中英

如何在Windows注冊表中設置一個值? (C ++)

[英]How to set a value in windows registry? (C++)

我想將“HKEY_LOCAL_MACHINE \\ Software \\ company name \\ game name \\ settings \\ value”鍵編輯為“1”(DWORD)

這是我的代碼:

HKEY hkey;
 DWORD dwDisposition;
 if(RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\company name\\game name\\settings"), 0, NULL, 0, 0, NULL, &hkey, &dwDisposition) == ERROR_SUCCESS){
  DWORD dwType, dwSize;
  dwType = REG_DWORD;
  dwSize = sizeof(DWORD);
  DWORD rofl = 1;
  RegSetValueEx(hkey, TEXT("value"), 0, dwType, (PBYTE)&rofl, dwSize); // does not create anything
  RegCloseKey(hkey);
 }

但它什么都沒做。 RegCreateKeyEx()是實際執行某項操作的唯一函數:僅在注冊表中創建“文件夾”。 那又一次如何失敗? 我如何在注冊表中創建“文件”?

始終檢查API函數的返回值。 你會看到RegSetValueEx()返回5,訪問被拒絕。 你沒有要求寫入權限。 固定:

  if(RegCreateKeyEx(HKEY_LOCAL_MACHINE, 
      TEXT("Software\\company name\\game name\\settings"), 
      0, NULL, 0, 
      KEY_WRITE, NULL, 
      &hkey, &dwDisposition) == ERROR_SUCCESS) {
    // etc..
  }

您可能需要將KEY_WRITE作為samDesired arugment的值傳遞給RegCreateKeyEx()函數(第六個參數)。

這是從實際代碼中復制和編輯,可能包含錯誤。

LONG
SetRegValue
    (
        const wchar_t* path
        ,const wchar_t *name
        ,const wchar_t *value
    )
{
    LONG status;
    HKEY hKey;

    status = RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_ALL_ACCESS, &hKey);
    if ( (status == ERROR_SUCCESS) && (hKey != NULL))
    {
        status = RegSetValueEx( hKey, name, 0, REG_SZ, (BYTE*)value, ((DWORD)wcslen(value) + 1)*sizeof(wchar_t));
        RegCloseKey(hKey);
    }
    return status;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM