程序自刪除的方式有很多,不過最終的思想不過是關閉本身進程,開啟新進程用於刪除自身。下面這個方法是用windows自帶命令行程序實現刪除。
命令行為 cmd.exe /c del filename
--------------------------------------------------------------------------------
代碼示例:C語言形式
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
BOOL SelfDel()
{
SHELLEXECUTEINFO sei;
TCHAR szModule [MAX_PATH],szComspec[MAX_PATH],szParams [MAX_PATH];
// 獲得自身文件名. 獲取cmd的全路徑文件名
if((GetModuleFileName(0,szModule,MAX_PATH)!=0) &&
(GetShortPathName(szModule,szModule,MAX_PATH)!=0) &&
(GetEnvironmentVariable("COMSPEC",szComspec,MAX_PATH)!=0))
{
// 設置命令參數.
lstrcpy(szParams,"/c del ");
lstrcat(szParams, szModule);
lstrcat(szParams, " > nul");
// 設置結構成員.
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;
// 創建cmd進程.
if(ShellExecuteEx(&sei))
{
// 設置cmd進程的執行級別為空閒執行,使本程序有足夠的時間從內存中退出.
SetPriorityClass(sei.hProcess,IDLE_PRIORITY_CLASS);
// 將自身進程的優先級置高
SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL);
// 通知Windows資源浏覽器,本程序文件已經被刪除.
SHChangeNotify(SHCNE_DELETE,SHCNF_PATH,szModule,0);
return TRUE;
}
}
return FALSE;
}
---------------------------------------------------------------------------------
代碼示例:匯編形式
.386
.model flat,stdcall
option casemap:none
include windows.inc
include kernel32.inc
includelib kernel32.lib
include urlmon.inc
includelib urlmon.lib
include shell32.inc
includelib shell32.lib
.data?
szModule db MAX_PATH dup (?)
sComspec db MAX_PATH dup (?); 自刪除
szParams db MAX_PATH dup (?)
hCurProcess dd ?
hCurThread dd ?
.data
sei SHELLEXECUTEINFO <0>
.const
szComspec db COMSPEC,0
Verb1 db open,0
szCom1 db /c del ,0
szCom2 db > nul,0
.code
start:
invoke GetModuleFileName,0,addr szModule,MAX_PATH
invoke GetEnvironmentVariable,addr szComspec,addr sComspec,MAX_PATH
invoke lstrcpy,addr szParams,addr szCom1
invoke lstrcat,addr szParams,addr szModule
invoke lstrcat,addr szParams,addr szCom2
mov sei.cbSize,sizeof sei ;1
mov sei.hwnd,0 ;2
mov sei.lpVerb,offset Verb1 ;3
lea eax,szParams
mov sei.lpParameters,eax ;4
lea eax,sComspec
mov sei.lpFile,eax ;5
mov sei.lpDirectory,0
mov sei.nShow,SW_HIDE
mov sei.fMask,SEE_MASK_NOCLOSEPROCESS
invoke ShellExecuteEx, addr sei
.if eax
invoke SetPriorityClass,sei.hProcess,IDLE_PRIORITY_CLASS
invoke GetCurrentProcess
mov hCurProcess,eax
invoke SetPriorityClass,hCurProcess,REALTIME_PRIORITY_CLASS
invoke GetCurrentThread
mov hCurThread,eax
invoke SetThreadPriority,hCurThread,THREAD_PRIORITY_TIME_CRITICAL
invoke SHChangeNotify,SHCNE_DELETE,SHCNF_PATH,addr szModule,0
&n