Posted on 2005-12-07 10:21
小明 閱讀(1256)
評論(1) 編輯 收藏 引用 所屬分類:
Win32
記得以前在程序員雜志上面,看見有人提到這個問題,試了很多種方法,結(jié)果是沒辦法將程序刪除。
真的沒辦法刪除自身么?
請運行下面的代碼:
#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
}
程序的思想是通過創(chuàng)建一個另外的進程(ShellExecuteEx),再賦予本進程比較高的權(quán)限(SetPriorityClass),
等這個程序退出以后,那個殺進程的進程就可以刪除程序了,另外程序通過SHChangeNotify通知Explorer:程序被刪除。
具體API的使用方法請看MSDN.
ps:這個程序是我在老外的網(wǎng)站上找到的,不是我寫的。我在VC6,Win2000 Professional上面調(diào)試通過