自分を削除

9078 ワード

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    btn1: TButton;
    btn2: TButton;
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
uses ShellAPI;

procedure DeleteMe;
var
  BatchFile: TextFile;
  BatchFileName: string;
  ProcessInfo: TProcessInformation;
  StartUpInfo: TStartupInfo;
begin
  BatchFileName := ExtractFilePath(ParamStr(0)) + '_deleteme.bat';

  AssignFile(BatchFile, BatchFileName);
  Rewrite(BatchFile);

  Writeln(BatchFile, ':try');
  Writeln(BatchFile, 'del "' + ParamStr(0) + '"');
  Writeln(BatchFile,
    'if exist "' + ParamStr(0) + '"' + ' goto try');
  Writeln(BatchFile, 'del %0');
  CloseFile(BatchFile);

  FillChar(StartUpInfo, SizeOf(StartUpInfo), $00);
  StartUpInfo.dwFlags := STARTF_USESHOWWINDOW;
  StartUpInfo.wShowWindow := SW_HIDE;

  if CreateProcess(nil, PChar(BatchFileName), nil, nil,
    False, IDLE_PRIORITY_CLASS, nil, nil, StartUpInfo,
    ProcessInfo)
  then
  begin
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);
  end;
end;


procedure DeleteMe2;
var
  BatchFile: TextFile;
  BatchFileName: string;
begin
  BatchFileName := ExtractFilePath(ParamStr(0)) + '_deleteme.bat';

  AssignFile(BatchFile, BatchFileName);
  Rewrite(BatchFile);

  Writeln(BatchFile, ':try');
  Writeln(BatchFile, 'del "' + ParamStr(0) + '"');
  Writeln(BatchFile,
    'if exist "' + ParamStr(0) + '"' + ' goto try');
  Writeln(BatchFile, 'del %0');
  CloseFile(BatchFile);

  {HINSTANCE ShellExecute(
    HWND hwnd,    // handle to parent window
    LPCTSTR lpOperation,    // pointer to string that specifies operation to perform
    LPCTSTR lpFile,    // pointer to filename or folder name string
    LPCTSTR lpParameters,    // pointer to string that specifies executable-file parameters 
    LPCTSTR lpDirectory,    // pointer to string that specifies default directory
    INT nShowCmd     // whether file is shown when opened
   );}
  //ShellExecute(handle, "open", path_to_folder, NULL, NULL, SW_SHOWNORMAL);
  //ShellExecute 0, "open", "cmd.exe", "/c /s copy C:\BOOT.INI C:\BOOT.bak", App.Path, 5
  //ShellExecute SetUp.hwnd, "open", "cmd.exe", "/c copy c:\Word1.doc", "d:\word2.doc", SW_SHOWNORMA
  ShellExecute(0,'open','cmd.exe',pchar(' /c '+BatchFileName),nil,SW_HIDE);
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  DeleteMe;
end;

procedure TForm1.btn2Click(Sender: TObject);
begin
  DeleteMe2;
end;

end.