Eliminar el ejecutable desde el propio ejecutable

El siguiente código elimina el ejecutable desde el propio programa, para ello se construye un fichero .bat que se inicia con la función WinExec.
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
  Button1: TButton;
  procedure Button1Click(Sender: TObject);
private
  { Private declarations }
public
  { Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
f : TextFile;
ficheroBat : string;
begin
ficheroBat := ChangeFileExt(Application.ExeName, '.bat');
AssignFile(f, ficheroBat);
FileMode := fmOpenWrite;
rewrite(f);
try
  Writeln(f, format('Erase "%s"',[Application.exename]));
  Writeln(f, format('Erase "%s"',[ficheroBat]));
finally
  CloseFile(f);
end;
WinExec (Pchar(ficheroBat), 1);
Application.terminate;
end;


end.
o aquí tienen otra función que copia el propio ejecutable al directorio raíz c:\ y lo ejecuta desde allí
PROGRAM Project1;

{©Drkb v.3(2007): www.drkb.ru,

®Vit (Vitaly Nevzorov) - nevzorov@yahoo.com}



USES

  Forms, classes, windows, Sysutils, ShellApi,

  Unit1 IN 'Unit1.pas' {Form1};



{$R *.RES}

VAR f: textFile;
  FileName: STRING;

BEGIN

  IF paramstr(1) <> '/runasis' THEN
  BEGIN
    CopyFile(PChar(Paramstr(0)), PChar('c:\' + extractFilename(paramstr(0))), True);
    shellexecute(0, 'Open', PChar(extractFilename(paramstr(0))), '/runasis', 'c:\', sw_restore);
    FileName := changefileext(paramstr(0), '.bat');
    assignFile(f, FileName);
    rewrite(f);
    writeln(f, ':1');
    writeln(f, format('Erase "%s"', [paramstr(0)]));
    writeln(f, format('If exist "%s" Goto 1', [paramstr(0)]));
    writeln(f, format('Erase "%s"', [FileName]));
    closefile(f);
    ShellExecute(0, 'Open', PChar(FileName), NIL, NIL, sw_hide);
  END
  ELSE
  BEGIN
    Application.Initialize;
    Application.CreateForm(TForm1, Form1);
    Application.Run;
  END;

END.

No hay comentarios:

Publicar un comentario