Skip to content

Commit

Permalink
管理员模式启动
Browse files Browse the repository at this point in the history
  • Loading branch information
Asteri5m committed Jun 25, 2024
1 parent fb9b0a4 commit 2a1341f
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions LazyDogTools.pro
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ SOURCES += \

HEADERS += \
PolicyConfig.h \
UAC.h \
audiomanager.h \
custom.h \
lazydog.h \
Expand Down
41 changes: 41 additions & 0 deletions UAC.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#ifndef UAC_H
#define UAC_H

#include <ShlObj_core.h>
#include <QCoreApplication>

// 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
3 changes: 3 additions & 0 deletions lazydog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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")
{
Expand Down
2 changes: 2 additions & 0 deletions lazydog.h
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ private slots:

public:
bool autoHidden = true;
bool adminStart = false;

private:
void InitSystemTray();
Expand All @@ -101,6 +102,7 @@ private slots:
void ShowDebugText(QString level, QString text);
void SaveBindListToXml();
BindList LoadBindListFromXml();
//json数据转为QMap
QMap<QString, QString> JsonToMap(QByteArray data);
void SaveSettingConfig();
bool SetAutostartAtPoweron(bool setFlag);
Expand Down
11 changes: 11 additions & 0 deletions main.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@

#include "lazydog.h"
#include "UAC.h"

#include <QApplication>

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) // 自动隐藏
Expand Down

0 comments on commit 2a1341f

Please sign in to comment.