Execute executable-independent program

3

I'm doing an updater, but at certain times, I need to update the executable, which is not possible since it's in use. I would have a way to swap the executables and run the program later.

    
asked by anonymous 18.10.2014 / 11:27

2 answers

4

I was able to do it, I found a form in this link: link

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.
    
18.10.2014 / 17:01
1

If the executable is in use, you may not be able to update it. In this case, if you decide to terminate 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 FindWindow routine to assist you.

    
05.03.2015 / 21:12