实现win客户端程序卸载功能

发布时间 2023-11-29 00:20:03作者: 香蕉储蓄所

方法1:
创建bat临时文件来删除安装目录下的文件:https://www.cnblogs.com/calm2012/archive/2013/05/31/3110474.html

方法2(看作是1的补充完善):
把卸载程序复制到临时目录,并设置FILE_FLAG_DELETE_ON_CLOSE,使用CreateProcess创建子进程,等待父进程结束再删除安装目录
链接:https://www.zhihu.com/question/565969510/answer/2789531847

Windows的CreateFile有个标记叫FILE_FLAG_DELETE_ON_CLOSE

关于FILE_FLAG_DELETE_ON_CLOSE的描述:
The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles.If there are existing open handles to a file, the call fails unless they were all opened with the FILE_SHARE_DELETE share mode.Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified.

  1. 使用CopyFile把可执行拷贝到临时目录,改为随机名字。
  2. 使用CreateFile使用FILE_SHARE_READ,带上FILE_FLAG_DELETE_ON_CLOSE打开这文件。
  3. CreateProcess或类似API执行临时目录这个文件
    • 这个新进程等待当前进程退出(可以在父进程创建一个命名共享内存,并写入进程号,标记当前进程为父进程,并在子进程读取并等待父进程结束,父子进程共用exe需要区分逻辑分支)
  4. 退出当前进程
  5. 新进程执行剩下的清理工作
  6. 新进程退出
  7. 进程退出时,系统会把这文件的HANDLE关掉,此时应该没有HANDLE指向这个临时文件。又因为有FILE_FLAG_DELETE_ON_CLOSE,这个临时文件也会被系统删掉。