QT 后台执行需要管理员权限的bat脚本
参考文章:
https://blog.youkuaiyun.com/qq_25177949/article/details/134133673
开发时遇到需要执行arp清除的问题,但必须以管理员权限执行,这个对于用户来说比较麻烦(会问你什么是管理员权限运行。。。),可以采用这种方式:
一、按参考文章中内容,写一段脚本,用于获取管理员权限
@echo off
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",0)(window.close)&&exit
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' (
echo Administrator rights confirmed.
) else (
echo Requesting administrator rights...
powershell Start-Process -FilePath "%0" -Verb RunAs
exit /b
)
#添加需要运行的脚本内容
arp -d
这里添加了第一行,使得脚本可以后台运行,而不会弹出黑色窗口被用户bb。。。
在最后添加所有想要运行的内容。
二、放在程序exe所在目录下
这里按喜好放,之后调用的时候修改即可。
三、调用
在适当位置插入QProcess,执行脚本,QProcess运行方式按自己需求即可。
QProcess* MyProcess = new QProcess(this);
//取exe所在目录
QString ExePath = QCoreApplication::applicationDirPath() + "/xxxx.bat";
//适时删除
connect(MyProcess , QOverload<int>::of(&QProcess::finished), this, [=](int exitCode) {
ArpProcess->deleteLater();
});
MyProcess ->start(ExePath);