Run executable independent program

Asked

Viewed 873 times

3

I am making a Updater, but at certain times, I need to update the executable, which is not possible since it is in use. You would have a way to swap the executables and run the program afterwards.

  • 1

    From what I understand, he closes the process, that’s it?

  • But Application.terminate in the middle of the program interrupts all of the later commands, no?

  • 1

    If it were . Net would have Clickonce.

  • 1

    @Thiagosilva and how would it be? Batch has its limitations

  • I have an article about this: http://edn.embarcadero.com/article/33973

2 answers

4


I managed to do, I found a way on this link: http://www.delphibr.com.br/artigos/atualizador.htm

More clearly, in this part:

program Atualizador;
{$APPTYPE CONSOLE}

uses
  SysUtils, Windows;

var
 min: integer;

begin
  DeleteFile('aplicativo.old'); // apaga um arquivo antigo, caso exista
  repeat // o truque: cria-se um laço até encerrar o aplicativo
    if RenameFile('aplicativo.exe','aplicativo.old') then // tenta renomear o exe
    begin
      RenameFile('aplicativo.new','aplicativo.exe'); // renomeia o novo como exe
      WinExec('aplicativo.exe',0); // executa novamente o aplicativo
      exit;
    end;
    min := 0;       // Se não for possível renomear é porque o aplicativo
    sleep(2000);    // não terminou por completo, espero 2 segundos e
    min := min + 1; // tento de novo. Espero até 20 segundos (contador)
 until min = 10;
end.
  • Yes, but continue only if you don’t update, note that you have an Exit; right on top, and only proceed if you don’t run it.

1

If the executable is in use, you may not be able to update it. In this case, if you feel you need to finish the process, you can use the following routine:

Procedure KillProcess( hWindowHandle: HWND );
Var
   hprocessID: INTEGER;
   processHandle: THandle;
   DWResult: DWORD;
Begin
   SendMessageTimeout( hWindowHandle, WM_CLOSE, 0, 0,
      SMTO_ABORTIFHUNG Or SMTO_NORMAL, 5000, DWResult );

   If isWindow( hWindowHandle ) Then
   Begin
      // PostMessage(hWindowHandle, WM_QUIT, 0, 0);
      { Get the process identifier for the window}
      GetWindowThreadProcessID( hWindowHandle, @hprocessID );
      If hprocessID <> 0 Then
      Begin
         { Get the process handle }
         processHandle := OpenProcess( PROCESS_TERMINATE Or PROCESS_QUERY_INFORMATION,
            False, hprocessID );
         If processHandle <> 0 Then
         Begin
            { Terminate the process }
            TerminateProcess( processHandle, 0 );
            CloseHandle( ProcessHandle );
         End;
      End;
   End;
End;

Note that this routine will work when you know the Handle of the running window. You can use the API’s Findwindow routine to assist you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.