Restart Delphi Application Programmatically

前端 未结 9 1462
情深已故
情深已故 2021-02-09 06:58

It should not be possible to run multiple instances of my application. Therefore the project source contains:

CreateMutex (nil, False, PChar (ID));
if (GetLastEr         


        
相关标签:
9条回答
  • 2021-02-09 08:00

    EDIT...

    OK. Now I belive that I know where is your problem... You have problems with program units finalization!

    Try to add at program section as first unit my bottom RestartMutex unit.

    program MyProgramName;  
    uses
      Mutex,
      Forms,
    ...
    

    ;

    unit RestartMutex;
    interface
    
    var
      Restart: boolean = false;
    
    implementation
    
    uses
      windows,
      ShellApi;
    
    var
      MutexHandle: cardinal;
      AppName: PChar;
    const
      ID = 'MyProgram';
    
    initialization
      MutexHandle := CreateMutex (nil, False, PChar (ID));
      if (GetLastError = ERROR_ALREADY_EXISTS) then
        Halt;
    
    finalization
      ReleaseMutex(MutexHandle);
      if Restart then
      begin
        AppName := PChar('MyProgramName.exe') ;
        ShellExecute(0,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
      end: 
    end.
    

    When you want to restart application just set variable Restart to true and than terminate an application.

    So, because is RestartMutex added as first in program section, this will couse that finalisation of unit RestartMutex will hepped nearly at the end of closing an application and all other units will do finalization before unit RestartMutex, that mean the Application can start safe again!

    0 讨论(0)
  • 2021-02-09 08:01

    Perhaps you should think outside the box. Instead of futzing with the mutex / instance logic, you could simply create another executable that waits for your app to close then starts it again. As an added bonus, you can later use this mechanism to, for example, update some of your main app's binaries. It's also much easier to run it elevated instead of maintaining different integrity levels inside the same app, etc.

    0 讨论(0)
  • 2021-02-09 08:02

    checkout this way:

    Simply runs a new application and kills the currernt one;

    http://www.delphitricks.com/source-code/windows/restart_the_own_program.html

    0 讨论(0)
提交回复
热议问题