'Delphi self-deleting program

How do I auto-delete, my Delphi program? I tried this code:

procedure DeleteSelf;
var
  module : HMODULE;
  buf : array [ 0 .. MAX_PATH - 1 ] of char;
  p : ULONG;
  hKrnl32 : HMODULE;
  pExitProcess, pDeleteFile, pFreeLibrary : pointer;
begin
  module := GetModuleHandle ( nil );
  GetModuleFileName ( module, buf, sizeof ( buf ) );
  CloseHandle ( THandle ( 4 ) );
  p := ULONG ( module ) + 1;
  hKrnl32 := GetModuleHandle ( 'kernel32' );
  pExitProcess := GetProcAddress ( hKrnl32, 'ExitProcess' );
  pDeleteFile := GetProcAddress ( hKrnl32, 'DeleteFileA' );
  pFreeLibrary := GetProcAddress ( hKrnl32, 'FreeLibrary' );
  asm
    lea eax, buf
    push 0
    push 0
    push eax
    push pExitProcess
    push p
    push pDeleteFile
    push pFreeLibrary
    ret
  end;
end;

But it does not work, do not delete the file. My program is console. Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source