可以使用Qt的QSettings类来读写注册表数据,也可以直接调用Windows API来读写注册表数据。
以下是调用Windows API读写注册表数据的示例代码:
```c++
#include <windows.h>
// 读取注册表中的字符串值
bool readRegistryString(HKEY hKey, const QString& subKey, const QString& valueName, QString& value)
{
HKEY hSubKey = NULL;
DWORD dwType = REG_SZ;
DWORD dwSize = 0;
if (RegOpenKeyEx(hKey, subKey.toStdWString().c_str(), 0, KEY_READ, &hSubKey) != ERROR_SUCCESS)
return false;
if (RegQueryValueEx(hSubKey, valueName.toStdWString().c_str(), NULL, &dwType, NULL, &dwSize) != ERROR_SUCCESS)
{
RegCloseKey(hSubKey);
return false;
}
if (dwType != REG_SZ)
{
RegCloseKey(hSubKey);
return false;
}
WCHAR* pBuffer = new WCHAR[dwSize / sizeof(WCHAR)];
if (RegQueryValueEx(hSubKey, valueName.toStdWString().c_str(), NULL, NULL, (LPBYTE)pBuffer, &dwSize) != ERROR_SUCCESS)
{
RegCloseKey(hSubKey);
delete[] pBuffer;
return false;
}
value = QString::fromWCharArray(pBuffer, dwSize / sizeof(WCHAR));
delete[] pBuffer;
RegCloseKey(hSubKey);
return true;
}
// 写入字符串值到注册表中
bool writeRegistryString(HKEY hKey, const QString& subKey, const QString& valueName, const QString& value)
{
HKEY hSubKey = NULL;
if (RegCreateKeyEx(hKey, subKey.toStdWString().c_str(), 0, NULL, 0, KEY_WRITE, NULL, &hSubKey, NULL) != ERROR_SUCCESS)
return false;
if (RegSetValueEx(hSubKey, valueName.toStdWString().c_str(), 0, REG_SZ, (LPBYTE)value.toStdWString().c_str(), (value.length() + 1) * sizeof(wchar_t)) != ERROR_SUCCESS)
{
RegCloseKey(hSubKey);
return false;
}
RegCloseKey(hSubKey);
return true;
}
int main(int argc, char *argv[])
{
// 读取注册表中的字符串值
QString value;
if (readRegistryString(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer", "Shell Folders", value))
qDebug() << value;
// 写入字符串值到注册表中
if (writeRegistryString(HKEY_CURRENT_USER, "Software\\MyCompany\\MyApp", "MyValue", "Hello World"))
qDebug() << "Write registry success.";
return 0;
}
```
以上代码演示了如何使用Windows API来读写注册表数据。其中,readRegistryString函数用于读取注册表中的字符串值,writeRegistryString函数用于将字符串值写入注册表中。在main函数中,我们首先使用readRegistryString函数读取注册表中的Shell Folders值,并输出到控制台上,然后使用writeRegistryString函数将字符串值Hello World写入到注册表中。