项目地址:https://github.com/zhangjiechina001/WatchDog
优快云现在上传资源要强制VIP才能下,牛逼!
主要功能
- 可配置是否开机自启
- 可设置程序监控周期
- 可通过界面设置需要监控的程序
2024.10.24 改进
将开机自启由修改配置文件改为添加到开始目录下,先将这脚本保存在资源文件中
@echo off
setlocal
rem Define the path to the target application and the shortcut name
set "TargetPath=%1" rem Modify this to the actual path of your application
set "ShortcutName=WatchDog" rem Name of the shortcut
rem Create Startup shortcut
set "StartupShortcut=C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\%ShortcutName%.lnk"
if not exist "%StartupShortcut%" (
powershell -Command "$WshShell = New-Object -ComObject WScript.Shell; $Shortcut = $WshShell.CreateShortcut('%StartupShortcut%'); $Shortcut.TargetPath = '%TargetPath%'; $Shortcut.WorkingDirectory = [System.IO.Path]::GetDirectoryName('%TargetPath%'); $Shortcut.IconLocation = '%TargetPath%'; $Shortcut.Save()"
echo Startup shortcut '%ShortcutName%' has been created.
) else (
echo Startup shortcut '%ShortcutName%' already exists.
)
endlocal
再从软件中读取替换字符,完成开机自启项添加
void AppUtils::addAppToStartup()
{
// 获取当前运行程序的路径
QString targetPath = QCoreApplication::applicationFilePath();
// 从资源文件读取批处理脚本
QFile batchFile(":/mybat.bat");
if (!batchFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "无法打开资源中的批处理文件。";
return;
}
// 读取脚本内容
QString scriptContent = batchFile.readAll();
batchFile.close();
// 替换占位符 %1 为实际的目标路径
scriptContent.replace("%1", "\"" + targetPath + "\"");
scriptContent.replace("%2", "\"" + QString("WatchDog") + "\"");
// 创建临时批处理文件
QTemporaryFile tempBatFile(QDir::temp().absoluteFilePath("CreateStartupShortcut.XXXXXX.bat"));
if (!tempBatFile.open()) {
qDebug() << "无法创建临时批处理文件。";
return;
}
// 将修改后的脚本内容写入临时文件
QTextStream out(&tempBatFile);
out << scriptContent;
// 关闭临时批处理文件
tempBatFile.close();
// 使用 QProcess 执行批处理文件
QProcess process;
process.start("cmd.exe", QStringList() << "/c" << tempBatFile.fileName());
process.waitForFinished();
// 可选:读取输出和错误信息(用于调试)
QString output = process.readAllStandardOutput();
QString error = process.readAllStandardError();
if (!output.isEmpty()) {
qDebug() << "输出:" << output;
}
if (!error.isEmpty()) {
qDebug() << "错误:" << error;
}
}
// 移除开机启动
void AppUtils::removeAppFromStartup()
{
QString startupFolder = "C:/ProgramData/Microsoft/Windows/Start Menu/Programs/StartUp/";
QString shortcutPath = startupFolder + QCoreApplication::applicationName() + ".lnk";
QFile shortcutFile(shortcutPath);
if (shortcutFile.exists()) {
if (shortcutFile.remove()) {
qDebug() << "Shortcut removed successfully.";
} else {
qDebug() << "Failed to remove shortcut.";
}
} else {
qDebug() << "Shortcut does not exist.";
}
}