欢迎访问Ningto's博客

Menu
  • 首页
  • 归档
  • 关于
  • 书签
  • 必应壁纸
  • IT聚合
  • 工具
    • 我的工具列表
    • 我的网盘
    • 必应每日壁纸API
    • Html转Markdown
    • 仙尘光标
Menu

卸载程序——自删除

最后更新 2021-08-10 19:17:05   阅读量 1185

Table of Contents

  • 1. 问题
  • 2. 分析
  • 3. 解决方法

问题

卸载程序在卸载的时候怎么把自己给删掉

分析

我们知道在删除文件的时候,这个文件不能被打开,如果是程序那程序不能在运行中。 通常卸载之前我们要求用户先关闭运行中的程序,或者强制杀掉进程,否则删除文件不彻底。 但由于卸载程序必须是在运行状态,所以我们没办法在运行中删除它。

解决方法

卸载程序在退出前生成delme.bat脚本文件,然后开启新进程执行脚本,执行脚本的时候要等待卸载程序退出。

生成delme.bat文件

其中mypath就是卸载程序的路径
sleep 2是在等待卸载进程退出

void Controller::writeDelMeBat(const QString &mypath)
{
    delmePath_ = mypath;
    delmePath_ = delmePath_.replace("/", "\\");

    qDebug() << "writeDelMeBat, path:" << delmePath_;
    QString dir = mypath.mid(0, mypath.lastIndexOf("\\"));
    QFile f(dir + "\\delme.bat");
    if (f.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
        QTextStream ts(&f);
        ts << "@ECHO OFF" << "\n";
        ts << "SETLOCAL" << "\n";
        ts << "powershell -nop -c \"& {sleep 2}\"" << "\n";
        ts << QString("DEL \"%1\"").arg(delmePath_) << "\n";
        ts << "DEL \"%~f0\"" << "\n";
    }
}

在退出的前一刻执行delme.bat

void Controller::executeDelMeBat()
{
    qInfo() << "delmepath:" << delmePath_;
    if (!delmePath_.isEmpty()) {
        QString dir = delmePath_.mid(0, delmePath_.lastIndexOf("\\"));
        QFile f(dir + "\\delme.bat");
        if (f.exists()) {
            QProcess process;
            process.setProgram("cmd.exe");
            process.setArguments({ "/C", R"(delme.bat)" });
            process.setWorkingDirectory(dir);
            process.setStandardOutputFile(QProcess::nullDevice());
            process.setStandardErrorFile(QProcess::nullDevice());
            bool ok = process.startDetached();
            qInfo() << "execute delme.bat, result:" << ok;
        }
    }
}
(转载本站文章请注明作者和出处:泞途 - ningto.com)

下一篇 – Python 更新xml文件非常方便
上一篇 – Qt怎样将gif作为窗口背景

  1. C/C++

toningto@outlook.com

推荐文章

Effective Python

Python的几种函数参数类型

标签云

MongoDB Mobile Boost Javascript Android Bug Mac Qt Windows Go Shell IOS Others Java Tools Design Tips Product Database Node.js Linux Python C/C++ Web MQ Life React

推广链接

【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

多谢支持,用了好几年,服务很稳定支持多设备!

其他

文章RSS

Copyright © 2016 Welcome To Ningto Blog | 鄂ICP备17003086号-2