开发者

Close and restart the current application in DELPHI

How can I do th开发者_开发技巧is one?

For some reason or selected by the user, “ask” the current application to restart it self.


uses ShellAPI;

...

procedure TForm1.RestartThisApp;
begin
  ShellExecute(Handle, nil, PChar(Application.ExeName), nil, nil, SW_SHOWNORMAL);
  Application.Terminate; // or, if this is the main form, simply Close;
end;


There is another way for closing-restarting the application:

Save a scheduled task to a short time after the application closes. This will have to be the VERY LAST thing your application does before exiting (no further data processing, saving, uploading or whatever)

eg.

  1. get the system time first
  2. set the scheduled task some time after this time (scheduled event will have to start your executable)
  3. exit your application (closing the main form or application.terminate will do it)

When your program starts again, it should check for any such scheduled task and remove them. This must be the VERY FIRST action your application should do when starting. (cleanup)

  1. check for any scheduled tasks created by your executable
  2. remove them

AFAIK, The Delphi Jedi component set has a component you can do the task scheduling stuff with.


I can add to @Andreas Rejbrand answer:

If the code is perfomed in .dpr file before Application.Initialize. for me it is better to call Halt(0) instead of Application.Terminate. I need it because on the first launch program does some installation and then restarts. If I call Application.Terminate main form blinks for a seconds (but it shouldn't be created at all!) and then application closes. So my code is following:

project.dpr:

if FirstRun then
begin
    DoFirstRunStuff();
    ShellExecute(Application.Handle, nil, PChar(Application.ExeName), nil, nil, SW_SHOWNORMAL);
    Halt(0);
end;
...
Application.Initialize;
Application.CreateForm(TMainForm, MainForm);
Application.Run;


You could have a separate simple restart.exe program that you run from your program and pass it the name of your executable file. Then close your program. The restart program can wait for a time, or until the executable file is read-writeable which seems to mean it is not running, then it can execute it and close itself.

I expect there is a better way to do this, maybe sombody can provide a better solution, but this function seems to tell me whether an executable is currently running:

function CanReadWriteFile(const f: TFileName): boolean;
var
  i: integer;
begin
  Result := false;
  i := FileOpen(f, fmOpenReadWrite);
  if i >= 0 then begin
    Result := true;
    FileClose(i);
  end;
end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜