如何写自删除的程序?

记得以前在 程序员杂志上面,看见有人提到这个问题,试了很多种方法,结果是没办法将程序删除。

真的没办法删除自身么?
请运行下面的代码:

#include <windows.h>
#include <shlobj.h>

BOOL SelfDelete()
{
  SHELLEXECUTEINFO sei;
  TCHAR szModule [MAX_PATH], szComspec[MAX_PATH], szParams [MAX_PATH];

  // get file path names:
  if((GetModuleFileName(0,szModule,MAX_PATH)!=0) &&
    (GetShortPathName(szModule,szModule,MAX_PATH)!=0) &&
    (GetEnvironmentVariable("COMSPEC",szComspec,MAX_PATH)!=0))
  {
    // set command shell parameters
    lstrcpy(szParams,"/c del ");
    lstrcat(szParams, szModule);
    lstrcat(szParams, " > nul");

    // set struct members
    sei.cbSize      = sizeof(sei);
    sei.hwnd        = 0;
    sei.lpVerb      = "Open";
    sei.lpFile      = szComspec;
    sei.lpParameters = szParams;
    sei.lpDirectory  = 0;
    sei.nShow        = SW_HIDE;
    sei.fMask        = SEE_MASK_NOCLOSEPROCESS;

    // increase resource allocation to program
    SetPriorityClass(GetCurrentProcess(),
                    REALTIME_PRIORITY_CLASS);
    SetThreadPriority(GetCurrentThread(),
                      THREAD_PRIORITY_TIME_CRITICAL);

    // invoke command shell
    if(ShellExecuteEx(&sei))
    {
      // suppress command shell process until program exits
      SetPriorityClass(sei.hProcess,IDLE_PRIORITY_CLASS);
      SetProcessPriorityBoost(sei.hProcess,TRUE);

      // notify explorer shell of deletion
      SHChangeNotify(SHCNE_DELETE,SHCNF_PATH,szModule,0);
      return TRUE;
    }
    else // if error, normalize allocation
    {
      SetPriorityClass(GetCurrentProcess(),
                      NORMAL_PRIORITY_CLASS);
      SetThreadPriority(GetCurrentThread(),
                        THREAD_PRIORITY_NORMAL);
    }
  }
  return FALSE;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR    lpCmdLine,
                    int      nCmdShow)
{
    // on program exit
    // close all handles etc.
    if(!SelfDelete())
    {
      // add error messaging
    }
    return 0;    // WinMain exit
  }


程序的思想是通过创建一个另外的进程(ShellExecuteEx),再赋予本进程比较高的权限(SetPriorityClass),
等这个程序退出以后,那个杀进程的进程就可以删除程序了,另外程序通过SHChangeNotify通知Explorer:程序被删除。

具体API的使用方法请看MSDN.

ps:这个程序是我在老外的网站上找到的,不是我写的。我在VC6,Win2000 Professional上面调试通过
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值