让程序自己更新本程序
先介绍一下 MOVEFILEEX 的使用.
移动文件:
MoveFileEx('c:\winnt\system32\xxxx.exe', 'd:\winnt.bak\system32\xxxx.exe',MOVEFILE_REPLACE_EXISTING);
MoveFileEx('c:\winnt\system32\xxxx.exe', 'd:\winnt.bak\system32\xxxx.exe',MOVEFILE_DELAY_UNTIL_REBOOT);
删除文件:
MoveFileEx('c:winnt\system32\xxxx.exe', nil,MOVEFILE_REPLACE_EXISTING);
MoveFileEx('c:winnt\system32\xxxx.exe', nil,MOVEFILE_DELAY_UNTIL_REBOOT);
我们再来看看用什么方法来实现程序自身的更新.
//拷贝副本,更新完删除副本,刚测试好
procedure StartUpdate;
var
vBatchFile: TextFile;
vBatchFileName,vUpdateName: string;
vProcessInfo: TProcessInformation;
vStartUpInfo: TStartupInfo;
begin
vBatchFileName := ExtractFilePath(ParamStr(0)) + '_deleteme.bat';
vUpdateName:=ParamStr(0)+'_Update.exe';
AssignFile(vBatchFile, vBatchFileName);
Rewrite(vBatchFile);
Writeln(vBatchFile, ':try');
Writeln(vBatchFile, 'Copy "'+ParamStr(0) + '" "'+vUpdateName+'"');
Writeln(vBatchFile, vUpdateName + ' /UPDATE');
Writeln(vBatchFile, 'del "' + vUpdateName + '"');
Writeln(vBatchFile,
'if exist "' + vUpdateName + '"' + ' goto try');
Writeln(vBatchFile, 'del %0');
CloseFile(vBatchFile);
FillChar(vStartUpInfo, SizeOf(vStartUpInfo), $00);
vStartUpInfo.dwFlags := STARTF_USESHOWWINDOW;
vStartUpInfo.wShowWindow := SW_HIDE;
if CreateProcess(nil, PChar(vBatchFileName), nil, nil,
False, IDLE_PRIORITY_CLASS, nil, nil, vStartUpInfo,
vProcessInfo) then
begin
CloseHandle(vProcessInfo.hThread);
CloseHandle(vProcessInfo.hProcess);
end;
end;
var
vBatchFile: TextFile;
vBatchFileName,vUpdateName: string;
vProcessInfo: TProcessInformation;
vStartUpInfo: TStartupInfo;
begin
vBatchFileName := ExtractFilePath(ParamStr(0)) + '_deleteme.bat';
vUpdateName:=ParamStr(0)+'_Update.exe';
AssignFile(vBatchFile, vBatchFileName);
Rewrite(vBatchFile);
Writeln(vBatchFile, ':try');
Writeln(vBatchFile, 'Copy "'+ParamStr(0) + '" "'+vUpdateName+'"');
Writeln(vBatchFile, vUpdateName + ' /UPDATE');
Writeln(vBatchFile, 'del "' + vUpdateName + '"');
Writeln(vBatchFile,
'if exist "' + vUpdateName + '"' + ' goto try');
Writeln(vBatchFile, 'del %0');
CloseFile(vBatchFile);
FillChar(vStartUpInfo, SizeOf(vStartUpInfo), $00);
vStartUpInfo.dwFlags := STARTF_USESHOWWINDOW;
vStartUpInfo.wShowWindow := SW_HIDE;
if CreateProcess(nil, PChar(vBatchFileName), nil, nil,
False, IDLE_PRIORITY_CLASS, nil, nil, vStartUpInfo,
vProcessInfo) then
begin
CloseHandle(vProcessInfo.hThread);
CloseHandle(vProcessInfo.hProcess);
end;
end;
作者: 陆岛工作室