讀寫windows注冊表


  最近有在做一寫讀寫配置文件的項目內容,了解到注冊表也可以寫配置,於是順便連接一下讀寫注冊表的內容。

MFC上讀寫注冊表

MFC的
CWinApp 類提供了很容易的注冊表訪問函數~~以前從來沒注意過~~還到處找讀寫注冊表的辦法~~ -_-! 看下面幾個成員函數~ 

SetRegistryKey Causes application settings to be stored in the registry instead of .INI files.

SetRegistryKey 這個函數功能是設置MFC程序的注冊表訪問鍵,並把讀寫 ini 文件的成員函數映射到讀寫注冊表。只要調用一下 SetRegistryKey 並指定注冊表鍵值,那么下面6個成員函數,就被映射到進行注冊表讀取了~

WriteProfileBinary Writes binary data to an entry in the application's .INI file.
WriteProfileInt Writes an integer to an entry in the application's .INI file.
WriteProfileString Writes a string to an entry in the application's .INI file.

GetProfileBinary Retrieves binary data from an entry in the application's .INI file.
GetProfileInt Retrieves an integer from an entry in the application's .INI file.
GetProfileString Retrieves a string from an entry in the application's .INI file.

MSDN上面寫上面6個函數是寫到INI文件的。所以俺就忽略了其訪問注冊表的功能。無意中看了其MFC實現才有所了解。

例子如下:
SetRegistryKey(_T("boli's app")); //這里是准備在注冊表HKEY_CURRENT_USER\\software 下面生成一個boli's app 分支~為什么說是准備呢?因為如果不調用相關函數,如上面提到的6個函數,它是不會真正讀寫注冊表的。具體本文最最下面的MFC實現摘錄。
CString strUserName,strPassword;
WriteProfileString("LogInfo","UserName",strUserName); //向注冊表HKEY_CURRENT_USER\\software\\boli's app\\LogInfo\\分支下寫入 UserName 字符串行鍵值~
WriteProfileString("LogInfo","Password",strPassword);//同上~

 strUserName = GetProfileString("LogInfo","UserName");// 這里是讀取HKEY_CURRENT_USER\\software\\boli's app\\LogInfo\\分支下的 UserName 字符串鍵值到 strUserName~
 strPassword =  GetProfileString("LogInfo","Password"); 

如果不是在CWinApp 派生的類中讀寫注冊表,可以直接用:
 strUserName = theApp.GetProfileString("LogInfo","UserName");
 strPassword = theApp.GetProfileString("LogInfo","Password");
或 
 strUserName = AfxGetApp()->GetProfileString("LogInfo","UserName");
條條大路通羅馬。



看看MFC的代碼吧~~SDK高手們不屑MFC,但有時候看看MFC的代碼會到學習SDK,windows api有很大的幫助~ :P
////////////////////////////////////////////////////////////////////////////
// CWinApp Settings Helpers

 

#ifdef AFX_INIT_SEG
#pragma code_seg(AFX_INIT_SEG)
#endif

void CWinApp::SetRegistryKey(LPCTSTR lpszRegistryKey)
{
     ASSERT(m_pszRegistryKey == NULL);
     ASSERT(lpszRegistryKey != NULL);
     ASSERT(m_pszAppName != NULL);

     BOOL bEnable = AfxEnableMemoryTracking(FALSE);
     free((void*)m_pszRegistryKey);
     m_pszRegistryKey = _tcsdup(lpszRegistryKey);
     free((void*)m_pszProfileName);
     m_pszProfileName = _tcsdup(m_pszAppName);
     AfxEnableMemoryTracking(bEnable);
}

void CWinApp::SetRegistryKey(UINT nIDRegistryKey)
{
     ASSERT(m_pszRegistryKey == NULL);

     TCHAR szRegistryKey[256];
     VERIFY(AfxLoadString(nIDRegistryKey, szRegistryKey));
     SetRegistryKey(szRegistryKey);
}

// returns key for HKEY_CURRENT_USER\"Software"\RegistryKey\ProfileName
// creating it if it doesn't exist
// responsibility of the caller to call RegCloseKey() on the returned HKEY
HKEY CWinApp::GetAppRegistryKey()
{
     ASSERT(m_pszRegistryKey != NULL);
     ASSERT(m_pszProfileName != NULL);

     HKEY hAppKey = NULL;
     HKEY hSoftKey = NULL;
     HKEY hCompanyKey = NULL;
     if (RegOpenKeyEx(HKEY_CURRENT_USER, _T("software"), 0, KEY_WRITE|KEY_READ,
      &hSoftKey) == ERROR_SUCCESS)
     {
          DWORD dw;
          if (RegCreateKeyEx(hSoftKey, m_pszRegistryKey, 0, REG_NONE,
           REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL,
           &hCompanyKey, &dw) == ERROR_SUCCESS)
             {
                   RegCreateKeyEx(hCompanyKey, m_pszProfileName, 0, REG_NONE,
                    REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL,
                    &hAppKey, &dw);
              }
 }
 if (hSoftKey != NULL)
  RegCloseKey(hSoftKey);
 if (hCompanyKey != NULL)
  RegCloseKey(hCompanyKey);

 return hAppKey;
}

// returns key for:
//      HKEY_CURRENT_USER\"Software"\RegistryKey\AppName\lpszSection
// creating it if it doesn't exist.
// responsibility of the caller to call RegCloseKey() on the returned HKEY
HKEY CWinApp::GetSectionKey(LPCTSTR lpszSection)
{
     ASSERT(lpszSection != NULL);

     HKEY hSectionKey = NULL;
     HKEY hAppKey = GetAppRegistryKey();
     if (hAppKey == NULL)
      return NULL;

     DWORD dw;
     RegCreateKeyEx(hAppKey, lpszSection, 0, REG_NONE,
      REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL,
          &hSectionKey, &dw);
     RegCloseKey(hAppKey);
     return hSectionKey;
}

UINT CWinApp::GetProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry,
 int nDefault)
{
     ASSERT(lpszSection != NULL);
     ASSERT(lpszEntry != NULL);
     if (m_pszRegistryKey != NULL) // use registry
     {
          HKEY hSecKey = GetSectionKey(lpszSection);
          if (hSecKey == NULL)
           return nDefault;
          DWORD dwValue;
          DWORD dwType;
          DWORD dwCount = sizeof(DWORD);
          LONG lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType,
           (LPBYTE)&dwValue, &dwCount);
          RegCloseKey(hSecKey);
          if (lResult == ERROR_SUCCESS)
          {
               ASSERT(dwType == REG_DWORD);
               ASSERT(dwCount == sizeof(dwValue));
               return (UINT)dwValue;
             }
             return nDefault;
   }
 else
 {
          ASSERT(m_pszProfileName != NULL);
          return ::GetPrivateProfileInt(lpszSection, lpszEntry, nDefault,
           m_pszProfileName);
     }

}

CString CWinApp::GetProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry,
 LPCTSTR lpszDefault)
{
 ASSERT(lpszSection != NULL);
 ASSERT(lpszEntry != NULL);
 if (m_pszRegistryKey != NULL)
 {
  HKEY hSecKey = GetSectionKey(lpszSection);
  if (hSecKey == NULL)
   return lpszDefault;
  CString strValue;
  DWORD dwType, dwCount;
  LONG lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType,
   NULL, &dwCount);
  if (lResult == ERROR_SUCCESS)
  {
   ASSERT(dwType == REG_SZ);
   lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType,
    (LPBYTE)strValue.GetBuffer(dwCount/sizeof(TCHAR)), &dwCount);
   strValue.ReleaseBuffer();
  }
  RegCloseKey(hSecKey);
  if (lResult == ERROR_SUCCESS)
  {
   ASSERT(dwType == REG_SZ);
   return strValue;
  }
  return lpszDefault;
 }
 else
 {
  ASSERT(m_pszProfileName != NULL);

  if (lpszDefault == NULL)
   lpszDefault = _T(""); // don't pass in NULL
  TCHAR szT[4096];
  DWORD dw = ::GetPrivateProfileString(lpszSection, lpszEntry,
   lpszDefault, szT, _countof(szT), m_pszProfileName);
  ASSERT(dw < 4095);
  return szT;
 }
}

BOOL CWinApp::GetProfileBinary(LPCTSTR lpszSection, LPCTSTR lpszEntry,
 BYTE** ppData, UINT* pBytes)
{
 ASSERT(lpszSection != NULL);
 ASSERT(lpszEntry != NULL);
 ASSERT(ppData != NULL);
 ASSERT(pBytes != NULL);
 *ppData = NULL;
 *pBytes = 0;
 if (m_pszRegistryKey != NULL)
 {
  HKEY hSecKey = GetSectionKey(lpszSection);
  if (hSecKey == NULL)
   return FALSE;

  DWORD dwType, dwCount;
  LONG lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType,
   NULL, &dwCount);
  *pBytes = dwCount;
  if (lResult == ERROR_SUCCESS)
  {
   ASSERT(dwType == REG_BINARY);
   *ppData = new BYTE[*pBytes];
   lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType,
    *ppData, &dwCount);
  }
  RegCloseKey(hSecKey);
  if (lResult == ERROR_SUCCESS)
  {
   ASSERT(dwType == REG_BINARY);
   return TRUE;
  }
  else
  {
   delete [] *ppData;
   *ppData = NULL;
  }
  return FALSE;
 }
 else
 {
  ASSERT(m_pszProfileName != NULL);

  CString str = GetProfileString(lpszSection, lpszEntry, NULL);
  if (str.IsEmpty())
   return FALSE;
  ASSERT(str.GetLength()%2 == 0);
  INT_PTR nLen = str.GetLength();
  *pBytes = UINT(nLen)/2;
  *ppData = new BYTE[*pBytes];
  for (int i=0;i<nLen;i+=2)
  {
   (*ppData)[i/2] = (BYTE)
    (((str[i+1] - 'A') << 4) + (str[i] - 'A'));
  }
  return TRUE;
 }
}

#ifdef AFX_CORE3_SEG
#pragma code_seg(AFX_CORE3_SEG)
#endif

BOOL CWinApp::WriteProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry,
 int nValue)
{
 ASSERT(lpszSection != NULL);
 ASSERT(lpszEntry != NULL);
 if (m_pszRegistryKey != NULL)
 {
  HKEY hSecKey = GetSectionKey(lpszSection);
  if (hSecKey == NULL)
   return FALSE;
  LONG lResult = RegSetValueEx(hSecKey, lpszEntry, NULL, REG_DWORD,
   (LPBYTE)&nValue, sizeof(nValue));
  RegCloseKey(hSecKey);
  return lResult == ERROR_SUCCESS;
 }
 else
 {
  ASSERT(m_pszProfileName != NULL);

  TCHAR szT[16];
  wsprintf(szT, _T("%d"), nValue);
  return ::WritePrivateProfileString(lpszSection, lpszEntry, szT,
   m_pszProfileName);
 }
}

BOOL CWinApp::WriteProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry,
   LPCTSTR lpszValue)
{
 ASSERT(lpszSection != NULL);
 if (m_pszRegistryKey != NULL)
 {
  LONG lResult;
  if (lpszEntry == NULL) //delete whole section
  {
   HKEY hAppKey = GetAppRegistryKey();
   if (hAppKey == NULL)
    return FALSE;
   lResult = ::RegDeleteKey(hAppKey, lpszSection);
   RegCloseKey(hAppKey);
  }
  else if (lpszValue == NULL)
  {
   HKEY hSecKey = GetSectionKey(lpszSection);
   if (hSecKey == NULL)
    return FALSE;
   // necessary to cast away const below
   lResult = ::RegDeleteValue(hSecKey, (LPTSTR)lpszEntry);
   RegCloseKey(hSecKey);
  }
  else
  {
   HKEY hSecKey = GetSectionKey(lpszSection);
   if (hSecKey == NULL)
    return FALSE;
   lResult = RegSetValueEx(hSecKey, lpszEntry, NULL, REG_SZ,
    (LPBYTE)lpszValue, (lstrlen(lpszValue)+1)*sizeof(TCHAR));
   RegCloseKey(hSecKey);
  }
  return lResult == ERROR_SUCCESS;
 }
 else
 {
  ASSERT(m_pszProfileName != NULL);
  ASSERT(lstrlen(m_pszProfileName) < 4095); // can't read in bigger
  return ::WritePrivateProfileString(lpszSection, lpszEntry, lpszValue,
   m_pszProfileName);
 }
}

BOOL CWinApp::WriteProfileBinary(LPCTSTR lpszSection, LPCTSTR lpszEntry,
 LPBYTE pData, UINT nBytes)
{
 ASSERT(lpszSection != NULL);
 if (m_pszRegistryKey != NULL)
 {
  LONG lResult;
  HKEY hSecKey = GetSectionKey(lpszSection);
  if (hSecKey == NULL)
   return FALSE;
  lResult = RegSetValueEx(hSecKey, lpszEntry, NULL, REG_BINARY,
   pData, nBytes);
  RegCloseKey(hSecKey);
  return lResult == ERROR_SUCCESS;
 }

 // convert to string and write out
 LPTSTR lpsz = new TCHAR[nBytes*2+1];
 UINT i;
 for (i = 0; i < nBytes; i++)
 {
  lpsz[i*2] = (TCHAR)((pData[i] & 0x0F) + 'A'); //low nibble
  lpsz[i*2+1] = (TCHAR)(((pData[i] >> 4) & 0x0F) + 'A'); //high nibble
 }
 lpsz[i*2] = 0;

 ASSERT(m_pszProfileName != NULL);

 BOOL bResult = WriteProfileString(lpszSection, lpszEntry, lpsz);
 delete[] lpsz;
 return bResult;
}

 

 

 
  1. #include <iostream>    
  2. #include <algorithm>    
  3. #include <cmath>    
  4. #include <vector>    
  5. #include <string>    
  6. #include <cstring>  
  7. #include <atlbase.h>  
  8. #include <Windows.h>  
  9. #pragma warning(disable:4996)    
  10. using namespace std;  
  11.   
  12. void read_dword()//讀取操作表,其類型為DWORD  
  13. {  
  14.     HKEY hKEY;//定義有關的鍵,在查詢結束時關閉  
  15.     //打開與路徑data_Set相關的hKEY  
  16.   
  17.     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1");   
  18.       
  19.     //訪問注冊表,hKEY則保存此函數所打開的鍵的句柄  
  20.     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_READ, &hKEY))  
  21.     {  
  22.         DWORD dwValue;//長整型數據,如果是字符串數據用char數組  
  23.         DWORD dwSize = sizeof(DWORD);  
  24.         DWORD dwType = REG_DWORD;  
  25.   
  26.         if (::RegQueryValueEx(hKEY, _T("123"), 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS)  
  27.         {  
  28.             cout << "錯誤:無法查詢有關的注冊表信息" << endl;  
  29.         }  
  30.   
  31.         cout << dwValue << endl;  
  32.     }  
  33.     ::RegCloseKey(hKEY);  
  34. }  
  35.   
  36. void read_reg_sz()//讀取操作表,其類型為REG_SZ  
  37. {  
  38.     HKEY hkey;  
  39.     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1");  
  40.   
  41.     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_READ, &hkey))  
  42.     {  
  43.         char dwValue[256];  
  44.         DWORD dwSzType = REG_SZ;  
  45.         DWORD dwSize = sizeof(dwValue);  
  46.         if (::RegQueryValueEx(hkey, _T("wangchong"), 0, &dwSzType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS)  
  47.         {  
  48.             cout << "無法查詢有關的注冊表信息" << endl;  
  49.         }  
  50.         cout << dwValue<< endl;  
  51.     }  
  52.     ::RegCloseKey(hkey);  
  53. }  
  54.   
  55. void write_dword()//在\Software\\Chicony\\Lenovo1文件夾下寫入一個test111的子鍵,設置其名稱為Name,其值為6  
  56. {  
  57.     HKEY hkey;//定義有關的hkey,在查詢結束時要關閉  
  58.     HKEY hTempKey;  
  59.       
  60.     DWORD dwValue = 6;  
  61.     DWORD dwSize = sizeof(DWORD);  
  62.     DWORD dwType = REG_DWORD;  
  63.   
  64.     LPCTSTR data_set= _T("Software\\Chicony\\Lenovo1");  
  65.     if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  66.     {  
  67.         if (ERROR_SUCCESS == ::RegCreateKey(hkey, _T("test111"), &hTempKey))  
  68.         {  
  69.             if (ERROR_SUCCESS != ::RegSetValueEx(hTempKey, _T("Name"), 0, REG_DWORD, (CONST BYTE*)&dwValue, sizeof(DWORD)))  
  70.             {  
  71.                 cout <<"寫入注冊表失敗"<< endl;  
  72.             }  
  73.         }  
  74.     }  
  75.     ::RegCloseKey(hkey);  
  76. }  
  77.   
  78. void write_reg_sz()  
  79. {  
  80.     HKEY hkey;  
  81.     HKEY hTempKey;     
  82.     char m_name_set[256]="China";  
  83.   
  84.     DWORD len = strlen(m_name_set) + 1;  
  85.     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1");  
  86.     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  87.     {  
  88.         if (ERROR_SUCCESS == ::RegCreateKey(hkey,_T("test1112"),&hTempKey))  
  89.         {  
  90.             if (ERROR_SUCCESS!=::RegSetValueEx(hTempKey,_T("Name"),0,REG_SZ,(const BYTE*)m_name_set,len))  
  91.             {  
  92.                 cout << "寫入錯誤" << endl;  
  93.             }  
  94.         }  
  95.     }  
  96.     ::RegCloseKey(hkey);  
  97. }  
  98.   
  99. void write_binary()  
  100. {  
  101.     HKEY hkey;  
  102.     HKEY hTempKey;  
  103.     BYTE m_name[10];  
  104.     memset(m_name, 0, sizeof(m_name));  
  105.     m_name[0] = 0xff;  
  106.     m_name[1] = 0xac;  
  107.     m_name[2] = 0x05;  
  108.     m_name[3] = 0x4e;  
  109.   
  110.     LPCTSTR data_set= _T("Software\\Chicony\\Lenovo1");  
  111.     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  112.     {  
  113.         if (ERROR_SUCCESS==::RegCreateKey(hkey,_T("test111"),&hTempKey))  
  114.         {  
  115.             if (ERROR_SUCCESS != ::RegSetValueEx(hTempKey, _T("Name"), 0, REG_BINARY, (unsigned char *)m_name, 5))  
  116.             {  
  117.                 cout << "寫入錯誤" << endl;  
  118.             }  
  119.         }  
  120.     }  
  121.     ::RegCloseKey(hkey);  
  122. }  
  123.   
  124. void delete_value()  
  125. {  
  126.     HKEY hkey;  
  127.     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1\\test1112");  
  128.   
  129.     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  130.     {  
  131.         if (ERROR_SUCCESS != ::RegDeleteValue(hkey, _T("Name")))  
  132.         {  
  133.             cout << "刪除錯誤" << endl;  
  134.         }  
  135.     }  
  136.     ::RegCloseKey(hkey);  
  137. }  
  138.   
  139. void delete_key()  
  140. {  
  141.     HKEY hkey;  
  142.     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1");  
  143.   
  144.     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  145.     {  
  146.         if (ERROR_SUCCESS != ::RegDeleteKey(hkey,"test1112"))  
  147.         {  
  148.             cout << "刪除錯誤" << endl;  
  149.         }  
  150.     }  
  151.     ::RegCloseKey(hkey);  
  152. }  
  153.   
  154. int main()  
  155. {      
  156.     read_dword();  
  157.     read_reg_sz();  
  158.     write_reg_sz();  
  159.     write_binary();  
  160.     delete_value();  
  161.     delete_key();  
  162.     system("pause");    
  163.     return 0;  
  164. }  
  165.  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM