设为首页 收藏本站
查看: 1043|回复: 0

[经验分享] 读写windows注册表

[复制链接]

尚未签到

发表于 2017-6-27 16:55:25 | 显示全部楼层 |阅读模式
  最近有在做一写读写配置文件的项目内容,了解到注册表也可以写配置,于是顺便连接一下读写注册表的内容。
MFC上读写注册表

MFC的
CWinApp 类提供了很容易的注册表访问函数~~以前从来没注意过~~还到处找读写注册表的办法~~ -_-! 看下面几个成员函数~
SetRegistryKeyCauses application settings to be stored in the registry instead of .INI files.
  SetRegistryKey 这个函数功能是设置MFC程序的注册表访问键,并把读写 ini 文件的成员函数映射到读写注册表。只要调用一下 SetRegistryKey 并指定注册表键值,那么下面6个成员函数,就被映射到进行注册表读取了~

WriteProfileBinaryWrites binary data to an entry in the application's .INI file.
WriteProfileIntWrites an integer to an entry in the application's .INI file.
WriteProfileStringWrites a string to an entry in the application's .INI file.

GetProfileBinaryRetrieves binary data from an entry in the application's .INI file.
GetProfileIntRetrieves an integer from an entry in the application's .INI file.
GetProfileStringRetrieves 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 - '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 & 0x0F) + 'A'); //low nibble
  lpsz[i*2+1] = (TCHAR)(((pData >> 4) & 0x0F) + 'A'); //high nibble
}
lpsz[i*2] = 0;
  ASSERT(m_pszProfileName != NULL);
  BOOL bResult = WriteProfileString(lpszSection, lpszEntry, lpsz);
delete[] lpsz;
return bResult;
}



  • #include <iostream>   
  • #include <algorithm>   
  • #include <cmath>   
  • #include <vector>   
  • #include <string>   
  • #include <cstring>  
  • #include <atlbase.h>  
  • #include <Windows.h>  
  • #pragma warning(disable:4996)   
  • using namespace std;  

  • void read_dword()//读取操作表,其类型为DWORD  
  • {
  •     HKEY hKEY;//定义有关的键,在查询结束时关闭  
  •     //打开与路径data_Set相关的hKEY  

  •     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1");   

  •     //访问注册表,hKEY则保存此函数所打开的键的句柄  
  •     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_READ, &hKEY))  
  •     {
  •         DWORD dwValue;//长整型数据,如果是字符串数据用char数组  
  •         DWORD dwSize = sizeof(DWORD);  
  •         DWORD dwType = REG_DWORD;  

  •         if (::RegQueryValueEx(hKEY, _T("123"), 0, &dwType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS)  
  •         {
  •             cout << "错误:无法查询有关的注册表信息" << endl;  
  •         }

  •         cout << dwValue << endl;
  •     }
  •     ::RegCloseKey(hKEY);
  • }

  • void read_reg_sz()//读取操作表,其类型为REG_SZ  
  • {
  •     HKEY hkey;  
  •     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1");  

  •     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_READ, &hkey))  
  •     {
  •         char dwValue[256];  
  •         DWORD dwSzType = REG_SZ;  
  •         DWORD dwSize = sizeof(dwValue);  
  •         if (::RegQueryValueEx(hkey, _T("wangchong"), 0, &dwSzType, (LPBYTE)&dwValue, &dwSize) != ERROR_SUCCESS)  
  •         {
  •             cout << "无法查询有关的注册表信息" << endl;  
  •         }
  •         cout << dwValue<< endl;
  •     }
  •     ::RegCloseKey(hkey);
  • }

  • void write_dword()//在\Software\\Chicony\\Lenovo1文件夹下写入一个test111的子键,设置其名称为Name,其值为6  
  • {
  •     HKEY hkey;//定义有关的hkey,在查询结束时要关闭  
  •     HKEY hTempKey;  

  •     DWORD dwValue = 6;  
  •     DWORD dwSize = sizeof(DWORD);  
  •     DWORD dwType = REG_DWORD;  

  •     LPCTSTR data_set= _T("Software\\Chicony\\Lenovo1");  
  •     if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  •     {
  •         if (ERROR_SUCCESS == ::RegCreateKey(hkey, _T("test111"), &hTempKey))  
  •         {
  •             if (ERROR_SUCCESS != ::RegSetValueEx(hTempKey, _T("Name"), 0, REG_DWORD, (CONST BYTE*)&dwValue, sizeof(DWORD)))  
  •             {
  •                 cout <<"写入注册表失败"<< endl;  
  •             }
  •         }
  •     }
  •     ::RegCloseKey(hkey);
  • }

  • void write_reg_sz()  
  • {
  •     HKEY hkey;  
  •     HKEY hTempKey;     
  •     char m_name_set[256]="China";  

  •     DWORD len = strlen(m_name_set) + 1;  
  •     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1");  
  •     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  •     {
  •         if (ERROR_SUCCESS == ::RegCreateKey(hkey,_T("test1112"),&hTempKey))  
  •         {
  •             if (ERROR_SUCCESS!=::RegSetValueEx(hTempKey,_T("Name"),0,REG_SZ,(const BYTE*)m_name_set,len))  
  •             {
  •                 cout << "写入错误" << endl;  
  •             }
  •         }
  •     }
  •     ::RegCloseKey(hkey);
  • }

  • void write_binary()  
  • {
  •     HKEY hkey;  
  •     HKEY hTempKey;  
  •     BYTE m_name[10];  
  •     memset(m_name, 0, sizeof(m_name));  
  •     m_name[0] = 0xff;
  •     m_name[1] = 0xac;
  •     m_name[2] = 0x05;
  •     m_name[3] = 0x4e;

  •     LPCTSTR data_set= _T("Software\\Chicony\\Lenovo1");  
  •     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  •     {
  •         if (ERROR_SUCCESS==::RegCreateKey(hkey,_T("test111"),&hTempKey))  
  •         {
  •             if (ERROR_SUCCESS != ::RegSetValueEx(hTempKey, _T("Name"), 0, REG_BINARY, (unsigned char *)m_name, 5))  
  •             {
  •                 cout << "写入错误" << endl;  
  •             }
  •         }
  •     }
  •     ::RegCloseKey(hkey);
  • }

  • void delete_value()  
  • {
  •     HKEY hkey;  
  •     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1\\test1112");  

  •     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  •     {
  •         if (ERROR_SUCCESS != ::RegDeleteValue(hkey, _T("Name")))  
  •         {
  •             cout << "删除错误" << endl;  
  •         }
  •     }
  •     ::RegCloseKey(hkey);
  • }

  • void delete_key()  
  • {
  •     HKEY hkey;  
  •     LPCTSTR data_set = _T("Software\\Chicony\\Lenovo1");  

  •     if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, data_set, 0, KEY_SET_VALUE, &hkey))  
  •     {
  •         if (ERROR_SUCCESS != ::RegDeleteKey(hkey,"test1112"))  
  •         {
  •             cout << "删除错误" << endl;  
  •         }
  •     }
  •     ::RegCloseKey(hkey);
  • }

  • int main()  
  • {
  •     read_dword();
  •     read_reg_sz();
  •     write_reg_sz();
  •     write_binary();
  •     delete_value();
  •     delete_key();
  •     system("pause");   
  •     return 0;  
  • }
  • DSC0000.png

DSC0001.png

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-388850-1-1.html 上篇帖子: Windows下VS2013 C++编译测试faster-rcnn 下篇帖子: WAMPServer的安装及配置-windows安装php环境
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表