1. 程式人生 > >那些你用的到的C++登錄檔操作

那些你用的到的C++登錄檔操作

獲取登錄檔資訊

以獲取cpu資訊為例

long lRet;
HKEY hKey;
TCHAR tcData[64];
DWORD dwSize;

lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
    _T("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"),
    0,
    KEY_QUERY_VALUE,
    &hKey
);

if (lRet == ERROR_SUCCESS)
{
    lRet = RegQueryValueEx(hKey,
        _T("ProcessorNameString"
), NULL, NULL, (LPBYTE)tcData, &dwSize ); if (lRet == ERROR_SUCCESS) { SetDlgItemText(IDC_STATIC_CPU, tcData); } else { AfxMessageBox(_T("RegQueryValueEx failed.")); } } else { AfxMessageBox(_T("RegOpenKeyEx failed."
)); } RegCloseKey(hKey);

獲取的是字串的方式

LONG lValue;
RegQueryValue(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\test"), NULL, &lValue);
TCHAR *pBuf = new TCHAR[lValue];
RegQueryValue(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\test"), pBuf, &lValue);
AfxMessageBox(pBuf);

獲取的是DWORD數值型的

HKEY hKey;
RegOpenKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\test"
)
, &hKey)
; DWORD dwType; DWORD dwValue; DWORD dwAge; RegQueryValueEx(hKey, _T("age"), 0, &dwType, (LPBYTE)&dwAge , &dwValue); CString str; str.Format(_T("age = %d"), dwAge); AfxMessageBox(str);

方式2

long lRet;
HKEY hKey;
DWORD dwAge;
DWORD dwSize;

lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
    _T("SOFTWARE\\test"),
    0,
    KEY_QUERY_VALUE,
    &hKey
);

if (lRet == ERROR_SUCCESS)
{
    lRet = RegQueryValueEx(hKey,
        _T("age"),
        0,
        NULL,
        (LPBYTE)&dwAge,
        &dwSize
    );
    if (lRet == ERROR_SUCCESS)
    {
        CString str;
        str.Format(_T("age = %d"), dwAge);
        AfxMessageBox(str);
    }
    else
    {
        AfxMessageBox(_T("RegQueryValueEx failed."));
    }
}
else
{
    AfxMessageBox(_T("RegOpenKeyEx failed."));
}

RegCloseKey(hKey);

寫入登錄檔

HKEY hKey;
//DWORD dw;
//RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\test"), 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_READ, NULL, &hKey, &dw);
//RegSetValueEx(hKey,_T("name") , 0, REG_SZ, (LPBYTE)_T("giantbranch"), 22);
RegCreateKey(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\test"), &hKey);
//增加預設
RegSetValue(hKey, NULL, REG_SZ, _T("giantbranch"), 11);
DWORD dwAge = 30;
RegSetValueEx(hKey, _T("age"), 0, REG_DWORD, (CONST BYTE *)&dwAge, 4);
RegCloseKey(hKey);