MFC操作注册表

1.创建和修改注册表

 1 BOOL CTestToolCtr::GetHkey(CString strHkey, HKEY& hkey)
 2 {
 3     if (0 == strHkey.CompareNoCase(_T("HKEY_CLASSES_ROOT")))
 4     {
 5         hkey = HKEY_CLASSES_ROOT;
 6     }
 7     else if (0 == strHkey.CompareNoCase(_T("HKEY_CURRENT_CONFIG")))
 8     {
 9         hkey = HKEY_CURRENT_CONFIG;
10     }
11     else if (0 == strHkey.CompareNoCase(_T("HKEY_CURRENT_USER")))
12     {
13         hkey = HKEY_CURRENT_USER;
14     }
15     else if (0 == strHkey.CompareNoCase(_T("HKEY_LOCAL_MACHINE")))
16     {
17         hkey = HKEY_LOCAL_MACHINE;
18     }
19     else if (0 == strHkey.CompareNoCase(_T("HKEY_USERS")))
20     {
21         hkey = HKEY_USERS;
22     }
23     else
24     {
25         return FALSE;
26     }
27     return TRUE;
28 }
29 
30 BOOL CTestToolCtr::CreateKey(CString strHkey, 
                   CString strSubKey,
                   CString strName,
                   CString strValue)
31 { 32 if (strSubKey.IsEmpty() || strName.IsEmpty() || strValue.IsEmpty()) 33 { 34 return FALSE; 35 }

38 HKEY hkey; 39 HKEY hNewkey; 40 41 if (!GetHkey(strHkey,hkey)) 42 { 43 return FALSE; 44 } 45 46 DWORD dwDisp; 47 if (ERROR_SUCCESS != RegCreateKeyEx(hkey, strSubKey, NULL, 48 NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, 49 NULL, &hNewkey, &dwDisp)) 50 { 51 return FALSE; 52 } 53 54 if(ERROR_SUCCESS != RegSetValueExA(hNewkey, strName, NULL, 55 REG_SZ, (const BYTE*)strValue.GetBuffer(), 56 strlen(strValue))) 57 { 58 RegCloseKey(hNewkey); 59 return FALSE; 60 } 61 62 RegCloseKey(hNewkey); 63 return TRUE; 64 }

2. 删除注册表

 1 BOOL CTestToolCtr::DelKey(CString strHkey, CString strSubKey, CString strName)
 2 {
 3     if (strSubKey.IsEmpty() || strName.IsEmpty())
 4     {
 5         return FALSE;
 6     }
9 HKEY hkey; 10 if (!GetHkey(strHkey,hkey)) 11 { 12 return FALSE; 13 } 14 15 if (SHDeleteValue(hkey,strSubKey,strName) != ERROR_SUCCESS) 16 { 17 return FALSE; 18 } 19 return TRUE; 20 }

3. 查询注册表

 1 BOOL CTestToolCtr::QueryKey(CString strHkey, 
                 CString strSubKey,
                  CString strName,
                 CString& strValue) 2 { 3 strValue.Empty(); 4 if (strSubKey.IsEmpty() || strName.IsEmpty()) 5 { 6 return FALSE; 7 } 8 9 HKEY hkey; 10 HKEY hNewkey; 11 if (!GetHkey(strHkey,hkey)) 12 { 13 return FALSE; 14 } 15 16 DWORD dwDisp; 17 if (ERROR_SUCCESS != RegCreateKeyEx(hkey, strSubKey, NULL, NULL, 18 REG_OPTION_VOLATILE, KEY_READ, NULL, 19 &hNewkey, &dwDisp)) 20 { 21 return FALSE; 22 } 23 24 char szData[512]; 25 memset(szData, 0, sizeof(szData)); 26 27 DWORD dwLength = sizeof(szData); 28 if (ERROR_SUCCESS != RegQueryValueExA(hNewkey, strName, NULL, NULL, 29 (LPBYTE)szData, &dwLength)) 30 { 31 RegCloseKey(hNewkey); 32 return FALSE; 33 } 34 strValue = szData; 35 RegCloseKey(hNewkey); 36 return TRUE; 37 38 }
高山流水,海纳百川!
原文地址:https://www.cnblogs.com/ahcc08/p/3690207.html