Restart Delphi Application Programmatically

前端 未结 9 1639
情深已故
情深已故 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!

提交回复
热议问题