QT 读取和写入注册表


#include <QSettings>

        #define RUN_KEY "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\windows\\CurrentVersion\\run"
        QSettings *pReg = new QSettings(RUN_KEY, QSettings::NativeFormat);
        
	pReg->setValue("key", "value"); //设置注册表值

        QVariant v = pReg->value("key"); //读取注册表值
        v.toString();
        delete reg;



  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt中,可以使用QSettings类来读取写入注册表。但是,修改注册表需要管理员权限。要获取管理员权限,可以使用Windows API的ShellExecute函数。 以下是一个示例代码,可以在Qt中获取管理员权限并修改注册表: ```cpp #include <QCoreApplication> #include <Windows.h> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // 获取管理员权限 SHELLEXECUTEINFO shexinfo = {0}; shexinfo.cbSize = sizeof(SHELLEXECUTEINFO); shexinfo.fMask = SEE_MASK_NOCLOSEPROCESS; shexinfo.lpVerb = L"runas"; shexinfo.lpFile = L"cmd.exe"; shexinfo.nShow = SW_HIDE; if (!ShellExecuteEx(&shexinfo)) { qDebug() << "Failed to get admin privileges!"; return a.exec(); } // 等待管理员权限获取完成 WaitForSingleObject(shexinfo.hProcess, INFINITE); // 写入注册表 HKEY hKey; QString keyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"; QString appName = "MyApp"; QString appPath = "C:\\MyApp\\MyApp.exe"; LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyPath.toStdWString().c_str(), 0, KEY_WRITE, &hKey); if (result != ERROR_SUCCESS) { qDebug() << "Failed to open registry key!"; return a.exec(); } result = RegSetValueEx(hKey, appName.toStdWString().c_str(), 0, REG_SZ, (LPBYTE)appPath.toStdWString().c_str(), (DWORD)(appPath.length() + 1) * sizeof(wchar_t)); if (result != ERROR_SUCCESS) { qDebug() << "Failed to write registry value!"; RegCloseKey(hKey); return a.exec(); } RegCloseKey(hKey); qDebug() << "Registry key updated successfully!"; return a.exec(); } ``` 在上面的代码中,我使用了Windows API的ShellExecute函数来获取管理员权限。然后,我打开了注册表项"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",并将我的应用程序路径写入注册表中。最后,我关闭了注册表项句柄和进程句柄。 请注意,修改注册表是危险的操作,需要谨慎处理。在实际应用中,您应该根据您的具体需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值