Mega Code Archive

 
Categories / Delphi / Examples
 

Selfdeletingexe

> Subject: Self-deleting executable The following code works. ************************************************************************** unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Label1: TLabel; procedure Button1Click(Sender: TObject); private { Private declarations } procedure DeleteSelf; public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} //********************************************************* procedure TForm1.DeleteSelf; //********************************************************* var F: TextFile; batName: string; pi: TProcessInformation; si: TStartupInfo; begin batName := ExtractFilePath(ParamStr(0)) + '$$$$$$$$.bat'; AssignFile(F,batName); Rewrite(F); Writeln(F,':try'); Writeln(F,'del "'+ParamStr(0)+'"'); Writeln(F,'if exist "'+ ParamStr(0)+'"'+' goto try'); Writeln(F,'del "' + batName + '"' ); CloseFile(F); FillChar(si, SizeOf(si), $00); si.dwFlags := STARTF_USESHOWWINDOW; si.wShowWindow := SW_HIDE; if CreateProcess( nil, PChar(batName), nil, nil, False, IDLE_PRIORITY_CLASS, nil, nil, si, pi ) then begin CloseHandle(pi.hThread); CloseHandle(pi.hProcess); end; end; procedure TForm1.Button1Click(Sender: TObject); begin DeleteSelf(); //comment out to close when program is closed or uncomment //to close the file instantly then delete Close; end; end.