diff --git a/LazyDogTools.pro b/LazyDogTools.pro index b712c18..d2d8b18 100644 --- a/LazyDogTools.pro +++ b/LazyDogTools.pro @@ -18,6 +18,7 @@ SOURCES += \ HEADERS += \ PolicyConfig.h \ + UAC.h \ audiomanager.h \ custom.h \ lazydog.h \ diff --git a/UAC.h b/UAC.h new file mode 100644 index 0000000..e091ef6 --- /dev/null +++ b/UAC.h @@ -0,0 +1,41 @@ +#ifndef UAC_H +#define UAC_H + +#include +#include + +// for IsUserAnAdmin() +#pragma comment (lib, "Shell32.lib") + +class UAC +{ +public: + // 以管理员权限启动一个新实例 + // true-启动了新实例 + // false-未启动新实例 + static bool runAsAdmin() + { + if (IsUserAnAdmin()) + { + return false; // 当前程序正以管理员权限运行 + } + + QStringList args = QCoreApplication::arguments(); // 获取命令行参数 + if (args.count() < 2 || args[1] != "runas") // 不带参数或参数不为"runas"时,即直接运行 + { + // 获取应用程序可执行文件的路径 + QString filePath = QCoreApplication::applicationFilePath(); + + // 以管理员权限,执行exe程序 + HINSTANCE ins = ShellExecuteA(nullptr, "runas", filePath.toStdString().c_str(), + "runas", nullptr, SW_SHOWNORMAL); + if (ins > (HINSTANCE)32) + { + return true; // 程序新实例启动成功 + } + } + return false; + } +}; + +#endif // UAC_H diff --git a/lazydog.cpp b/lazydog.cpp index dc3648b..4920bc5 100644 --- a/lazydog.cpp +++ b/lazydog.cpp @@ -166,7 +166,10 @@ void LazyDog::InitSettingConfig() ui->checkBox_autostart->setChecked(true); if (lazyconfig.value(Config.Adminstart) == "true") + { ui->checkBox_adminstart->setChecked(true); + adminStart = true; + } if (lazyconfig.value(Config.Autochecknew) == "true") { diff --git a/lazydog.h b/lazydog.h index d6ce1c4..884db73 100644 --- a/lazydog.h +++ b/lazydog.h @@ -89,6 +89,7 @@ private slots: public: bool autoHidden = true; + bool adminStart = false; private: void InitSystemTray(); @@ -101,6 +102,7 @@ private slots: void ShowDebugText(QString level, QString text); void SaveBindListToXml(); BindList LoadBindListFromXml(); + //json数据转为QMap QMap JsonToMap(QByteArray data); void SaveSettingConfig(); bool SetAutostartAtPoweron(bool setFlag); diff --git a/main.cpp b/main.cpp index cfdc428..d63f044 100644 --- a/main.cpp +++ b/main.cpp @@ -1,5 +1,6 @@ #include "lazydog.h" +#include "UAC.h" #include @@ -7,6 +8,16 @@ int main(int argc, char *argv[]) { QApplication a(argc, argv); LazyDog w; + + // 以管理员权限启动一个新实例 + if (w.adminStart) + { + if (UAC::runAsAdmin()) + { + return 0; // 启动成功,当前程序退出 + } // 未启动,当前程序继续 + } + w.show(); if (w.autoHidden) // 自动隐藏