常用代码(Delphi 自我复制自我删除)
说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。
Delphi 自我复制源码 这种方法的原理是程序运行时先查看自己是不是在特定目录下,如果是就继续运行,如果不是就把自己拷贝到特定目录下,然后运行新程序,再退出旧程序. 打开Delphi,新建一个工程,在窗口的Create事件中写代码: procedure TForm1.FormCreate(Sender: TObject); var myname: string; begin myname := ExtractFilename(Application.Exename); //获得文件名 if application.Exename <> GetWindir + myname then //如果文件不是在Windows\System\那么.. begin copyfile(pchar(application.Exename), pchar(GetWindir + myname), False);{将自己拷贝到Windows\System\下} Winexec(pchar(GetWindir + myname), sw_hide);//运行Windows\System\下的新文件 application.Terminate;//退出 end; end; 其中GetWinDir是自定义函数,起功能是找出Windows\System\的路径. function GetWinDir: String; var Buf: array[0..MAX_PATH] of char; begin GetSystemDirectory(Buf, MAX_PATH); Result := Buf; if Result[Length(Result)]<>'\' then Result := Result + '\'; end; Delphi 程序自删除. 运行Delphi,新建一个工程,添加一个Button到窗体上,全部代码如下: unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure DeleteMe; //自定义程序自杀过程 procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); begin DeleteMe; end; procedure TForm1.DeleteMe; //程序自杀 //----------------------------------------------------------- function GetShortName(sLongName: string): string; //转换长文件名 var sShortName: string; nShortNameLen: integer; begin SetLength(sShortName, MAX_PATH); nShortNameLen := GetShortPathName(PChar(sLongName), PChar(sShortName), MAX_PATH - 1); if (0 = nShortNameLen) then begin // handle errors... end; SetLength(sShortName, nShortNameLen); Result := sShortName; end; //------------------------------------------------- var BatchFile: TextFile; BatchFileName: string; ProcessInfo: TProcessInformation; StartUpInfo: TStartupInfo; begin BatchFileName := ExtractFilePath(ParamStr(0)) + '$$Delme$$.bat'; AssignFile(BatchFile, BatchFileName); Rewrite(BatchFile); Writeln(BatchFile, ':try'); Writeln(BatchFile, 'del "' + GetShortName(ParamStr(0)) + '"'); Writeln(BatchFile, 'if exist "' + GetShortName(ParamStr(0)) + '"' + ' goto try'); Writeln(BatchFile, 'del %0'); Writeln(BatchFile, 'cls'); Writeln(BatchFile, 'exit'); 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; Application.Terminate; end; end. 本文来源:https://www.wddqw.com/doc/64c7ca32a21614791611281c.html