Qt Windows使用管理员权限运行Cmd

在Qt跨平台开发中,在Windows平台上经常有开启新的进程来执行任务的情况,这里又分为2种,一种是不需要超级管理员权限的,可以直接使用QProcess来完成;还有一种就是需要管理员权限来执行一些脚本。

比如现在想在软件打开时修改注册表,bat脚本如下:

bash 复制代码
@echo "auto create dump"
echo Yes | reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps"
echo Yes | reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\FTIRDasAnalyzer.exe"
echo Yes | reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\FTIRDasAnalyzer.exe" /v DumpFolder /t REG_EXPAND_SZ /d "C:\DumpFile" /f
echo Yes | reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\FTIRDasAnalyzer.exe" /v DumpType /t REG_DWORD /d 2 /f
echo Yes | reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\FTIRDasAnalyzer.exe" /v DumpCount /t REG_DWORD /d 10 /f

这时需要使用Windows平台的API,先加上windows.h头文件:

arduino 复制代码
#include <windows.h>

然后使用SHELLEXECUTEINFO相关API即可:

ini 复制代码
void UACrunProcess(QString Path) {
    QFile file(Path);
    if (!file.exists()) {
        logWarn() << "create dump bat path is not exists";
        return;
    }
    std::wstring wstr = Path.toStdWString();
    const wchar_t* filePtr = wstr.c_str();

    SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
    sei.lpVerb = TEXT("runas");
    sei.lpFile = filePtr;
    sei.nShow = SW_SHOWNORMAL;//without this,the windows will be hiden
//    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
        DWORD dwStatus = GetLastError();
        if (dwStatus == ERROR_CANCELLED) {
            logWarn() << "bat execute canceld";
        } else if (dwStatus == ERROR_FILE_NOT_FOUND) {
            logWarn() << "bat execute not found execute file";
        }
    }
}

上面代码比较简单,但是有几点需要注意:

  • 对于QString类型的字符串,需要转换为wchar_t*类型。
  • 在启动Qt Creator时必须以管理员权限启动。
  • 在执行过程中,可以通过echo Yes | ...的方式给指令在执行时赋默认值,否则黑色的命令行弹窗不会消失,会影响美观或者升级等操作。
相关推荐
看到我,请让我去学习4 小时前
Qt编程-qml操作(js,c++,canvas)
开发语言·qt
哈市雪花5 小时前
相机:Camera原理讲解(使用OpenGL+QT开发三维CAD)
qt·3d·交互·相机·图形学·opengl·视角
津津有味道7 小时前
Qt C++串口SerialPort通讯发送指令读写NFC M1卡
linux·c++·qt·串口通信·serial·m1·nfc
feiyangqingyun9 小时前
全网唯一/Qt结合ffmpeg实现手机端采集摄像头推流到rtsp或rtmp/可切换前置后置摄像头/指定分辨率帧率
qt·智能手机·ffmpeg
随意02310 小时前
Qt 事件
开发语言·qt
鸥梨菌Honevid10 小时前
Qt自定义控件(1)——QPaintEvent
开发语言·qt
Mr_Xuhhh1 天前
网络基础(1)
c语言·开发语言·网络·c++·qt·算法
feiyangqingyun1 天前
Qt音视频开发技巧/推流带旋转角度/rtsprtmp推流/保存文件到MP4/拉流解析旋转角度
qt·音视频·qt旋转角度推流
清醒的兰1 天前
Qt 基于TCP套接字编程
网络·qt·tcp
mahuifa11 天前
PySide环境配置及工具使用
python·qt·环境配置·开发经验·pyside