那些你用的到的C++注册表操作

获取注册表信息

以获取cpu信息为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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);

获取的是字符串的方式

1
2
3
4
5
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数值型的

获取的是DWORD数值型的

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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);

写入注册表

1
2
3
4
5
6
7
8
9
10
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);
自愿打赏专区