C语言程序自删除
程序自删除的方式有很多,不过最终的思想不过是关闭本身进程,开启新进程用于删除自身。下面这个方法是用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.incinclude 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
补充:软件开发 , C语言 ,