Module name: DeleteMe.cpp Written by: Jeffrey Richter Description: Allows an EXEcutable file to delete itself **************************************************/
#include #include #include
/////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE h, HINSTANCE b, LPSTR psz, int n) {
// Is this the Original EXE or the clone EXE? // If the command-line 1 argument, this is the Original EXE // If the command-line >1 argument, this is the clone EXE
if (__argc == 1) {
// Original EXE: Spawn clone EXE to delete this EXE // Copy this EXEcutable image into the user''s temp Directory
//***注重了***: // Open the clone EXE using FILE_FLAG_DELETE_ON_CLOSE HANDLE hfile = CreateFile(szPathClone, 0, FILE_SHARE_READ, NULL, OPEN_EXISTI NG, FILE_FLAG_DELETE_ON_CLOSE, NULL);
// Spawn the clone EXE passing it our EXE''s PRocess handle // and the full path name to the Original EXE file. TCHAR szCmdLine[512]; HANDLE hProcessOrig = OpenProcess(SYNCHRONIZE, TRUE, GetCurrentProcessId());
// This original process can now terminate. } else {
// Clone EXE: When original EXE terminates, delete it HANDLE hProcessOrig = (HANDLE) _ttoi(__targv[1]); WaitForSingleObject(hProcessOrig, INFINITE); CloseHandle(hProcessOrig); DeleteFile(__targv[2]); // Insert code here to remove the subdirectory too (if desired).
// The system will delete the clone EXE automatically // because it was opened with FILE_FLAG_DELETE_ON_CLOSE