Listing 3 A self-deleting executable
#include <windows.h> #include "SelfDelete.h" void WriteResourceToFile(HINSTANCE hInstance, int idResource, char const *filename) { // access the binary resource HRSRC hResInfo = FindResource(hInstance, MAKEINTRESOURCE(idResource), MAKEINTRESOURCE(RC_BINARYTYPE)); HGLOBAL hgRes = LoadResource(hInstance, hResInfo); void *pvRes = LockResource(hgRes); DWORD cbRes = SizeofResource(hInstance, hResInfo); // write the binary resource to a file HANDLE hFile = CreateFile(filename, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); DWORD cbWritten; WriteFile(hFile, pvRes, cbRes, &cbWritten, 0); CloseHandle(hFile); } void SelfDelete(HINSTANCE hInstance) { WriteResourceToFile(hInstance, ID_MAGICDEL_DLL, "magicdel.dll"); // Build command line // 1. Find rundll32.exe char commandLine[MAX_PATH * 3]; GetWindowsDirectory(commandLine, sizeof(commandLine)); lstrcat(commandLine, "\\rundll32.exe"); if (GetFileAttributes(commandLine) == INVALID_FILE_ATTRIBUTES) { GetSystemDirectory(commandLine, sizeof(commandLine)); lstrcat(commandLine, "\\rundll32.exe"); } // 2. Add rundll32.exe parameters lstrcat(commandLine, " magicdel.dll,_MagicDel@16 "); // 3. Add this file name char thisName[MAX_PATH]; GetModuleFileName(hInstance, thisName, sizeof(thisName)); lstrcat(commandLine, thisName); // Execute the command line PROCESS_INFORMATION procInfo; STARTUPINFO startInfo; memset(&startInfo, 0, sizeof(startInfo)); startInfo.dwFlags = STARTF_FORCEOFFFEEDBACK; CreateProcess(0, commandLine, 0, 0, FALSE, NORMAL_PRIORITY_CLASS, 0, 0, &startInfo, &procInfo); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { SelfDelete(hInstance); }