Delphi程序自删除代码
1 unit Unit1; 2 3 interface 4 5 uses 6 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 7 Dialogs, StdCtrls, jpeg, ExtCtrls; 8 9 type 10 TForm1 = class(TForm) 11 Image1: TImage; 12 Button1: TButton; 13 procedure Button1Click(Sender: TObject); 14 private 15 procedure My_DeleteMe; 16 { Private declarations } 17 public 18 { Public declarations } 19 end; 20 21 var 22 Form1: TForm1; 23 24 implementation 25 26 {$R *.dfm} 27 28 procedure TForm1.My_DeleteMe; //程序自杀 29 //----------------------------------------------------------- 30 function GetShortName(sLongName: string): string; //转换长文件名 31 var 32 sShortName: string; 33 nShortNameLen: integer; 34 begin 35 SetLength(sShortName, MAX_PATH); 36 nShortNameLen := GetShortPathName(PChar(sLongName), 37 PChar(sShortName), MAX_PATH - 1); 38 if (0 = nShortNameLen) then 39 begin 40 // handle errors... 41 end; 42 SetLength(sShortName, nShortNameLen); 43 Result := sShortName; 44 end; 45 //------------------------------------------------- 46 var 47 BatchFile: TextFile; 48 BatchFileName: string; 49 ProcessInfo: TProcessInformation; 50 StartUpInfo: TStartupInfo; 51 begin 52 BatchFileName := ExtractFilePath(ParamStr(0)) + '$$a$$.bat'; 53 AssignFile(BatchFile, BatchFileName); 54 Rewrite(BatchFile); 55 Writeln(BatchFile, ':try'); 56 Writeln(BatchFile, 'del "' + GetShortName(ParamStr(0)) + '"'); 57 Writeln(BatchFile, 'if exist "' + GetShortName(ParamStr(0)) + '"' + ' goto try'); 58 Writeln(BatchFile, 'del %0'); 59 Writeln(BatchFile, 'cls'); 60 Writeln(BatchFile, 'exit'); 61 CloseFile(BatchFile); 62 FillChar(StartUpInfo, SizeOf(StartUpInfo), $00); 63 StartUpInfo.dwFlags := STARTF_USESHOWWINDOW; 64 StartUpInfo.wShowWindow := SW_Hide; 65 if CreateProcess(nil, PChar(BatchFileName), nil, nil, 66 False, IDLE_PRIORITY_CLASS, nil, nil, StartUpInfo, 67 ProcessInfo) then 68 begin 69 CloseHandle(ProcessInfo.hThread); 70 CloseHandle(ProcessInfo.hProcess); 71 end; 72 Application.Terminate; 73 end; 74 75 76 77 procedure TForm1.Button1Click(Sender: TObject); 78 begin 79 MessageBeep(MB_ICONEXCLAMATION ); 80 My_DeleteMe; 81 end; 82 83 end.