您的位置:首页 > 编程语言 > C语言/C++

C/C++读写注册表中二进制数据(代码示例)

2020-03-11 17:52 615 查看

1、RegOpenKeyEx 函数:

原形:

LONG RegOpenKeyEx(  
            HKEY hKey,     // 要打开主键名  
            LPCTSTR lpSubKey, // 需要打开的子键或路径  
            DWORD ulOptions,  // 保留,为0 
            REGSAM samDesired, // 操作权限标志  
            PHKEY phkResult  // 指向你打开键的句柄 (通过指针返回) 
      );  

  返回值:不成功返回非0,成功返回ERROR_SUCCESS.  
  解释:该函数负责打开指定的键或子键,如果不存在他不建立。

  查看微软官方文档:http://msdn.microsoft.com/zh-cn/aa912084

2、RegSetValueEx函数:

 原形:

LONG RegSetValueEx(  
            HKEY hKey,      // 已打开的键的句柄  
            LPCTSTR lpValueName, // 要查询值的名称,传如\"\"为查询键下的默认值  
            DWORD Reserved,   // 保留  
            DWORD dwType,    // 写入键值的类型  
            CONST BYTE *lpData, // 变量数据的地址  
            DWORD cbData     // 变量的长度  
      );  

 返回值:不成功返回非0,成功返回ERROR_SUCCESS  
 解释:设置某子键下特定名称的值。

查看微软官方文档:http://msdn.microsoft.com/zh-cn/aa916717#

3、RegQueryValueEx函数:

原形:

LONG RegQueryValueEx(  
            HKEY hKey,      // 已打开的键的句柄  
            LPTSTR lpValueName, // 要查询值的名称,传如\"\"为查询键下的默认值  
            LPDWORD lpReserved, // 保留,为0  
            LPDWORD lpType,   // 查询的类型  
            LPBYTE lpData,    // 数据存放的地址  
            LPDWORD lpcbData   // 数据长度+1  
      );  

  返回值:不成功返回非0,成功返回ERROR_SUCCESS  
  解释:读取某子键下特定名称的值。

  查看微软官方文档:http://msdn.microsoft.com/zh-cn/aa914692

写入二进制数据代码示例:

# include <windows.h>
# include <tchar.h>

int main(void)
{
HKEY hKey;
HKEY rootKey = HKEY_CURRENT_USER;
TCHAR * subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
"\\MenuOrder\\Start Menu2\\Programs\\test";
TCHAR * keyValue = "c:\\test.exe";
long openReg;
long setRegValue;
DWORD dwType = REG_BINARY;
BYTE value[256] = "c:\\test.exe";
openReg = RegOpenKeyEx(rootKey, subKey, 0, KEY_WRITE, &hKey);
if (openReg == ERROR_SUCCESS)
{
setRegValue = RegSetValueEx(hKey, _T("order"), 0, dwType, value, 256);
if (setRegValue == ERROR_SUCCESS)
{
MessageBox(NULL, _T("Write Sucess"), _T("call"), MB_OK);
}
else
{
MessageBox(NULL, _T("Write Fail"), _T("call"), MB_OK);
}
RegCloseKey(hKey);
}
return 0;
}

读取二进制数据的代码示例:

# include <windows.h>
# include <tchar.h>

int main(void)
{
HKEY hKey;
HKEY rootKey = HKEY_CURRENT_USER;
TCHAR * subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
"\\MenuOrder\\Start Menu2\\Programs\\test";
long openRegResult;
long readRegResult;
DWORD dwType = REG_BINARY;
REGSAM mode = KEY_READ;
BYTE value[256] = {0};
DWORD length = 256;
openRegResult = RegOpenKeyEx(rootKey, subKey, 0, mode, &hKey);
if (ERROR_SUCCESS == openRegResult)
{
readRegResult = RegQueryValueEx(hKey, _T("order"), 0, &dwType, value, &length);
if (ERROR_SUCCESS == readRegResult)
{
MessageBox(NULL, _T(value), _T("call"), MB_OK);
}
else
{
MessageBox(NULL, _T("ERROR"), _T("call"), MB_OK);
}
}
RegCloseKey(hKey);
return 0;
}

注:读写其他类型的注册表键值与上述的类似,不单独讲解了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息