Suspend Process / Resume Process

Post date: Feb 8, 2010 11:33:53 AM

Sometimes, it may not be possible to start a process in suspended state for editing [CreateProcessA with PROCESS_SUSPENDED parameter] and it may be necessary to suspend an already running process. Code is also included for resuming a suspended process.

Coder: steve10120

Resume Process:

Function ResumeProcess(ProcessID: DWORD): Boolean;
var
  Snapshot,cThr: DWORD;
  ThrHandle: THandle;
  Thread:TThreadEntry32;
begin
  Result := False;
  cThr := GetCurrentThreadId;
  Snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
  if Snapshot <> INVALID_HANDLE_VALUE then
   begin
    Thread.dwSize := SizeOf(TThreadEntry32);
    if Thread32First(Snapshot, Thread) then
     repeat
      if (Thread.th32ThreadID <> cThr) and (Thread.th32OwnerProcessID = ProcessID) then
       begin
        ThrHandle := OpenThread(THREAD_ALL_ACCESS, false, Thread.th32ThreadID);
        if ThrHandle = 0 then Exit;
        ResumeThread(ThrHandle);
        CloseHandle(ThrHandle);
       end;
     until not Thread32Next(Snapshot, Thread);
     Result := CloseHandle(Snapshot);
    end;
end;

Suspend Process:

function SuspendProcess(PID:DWORD):Boolean;
var
hSnap:  THandle;
THR32:  THREADENTRY32;
hOpen:  THandle;
begin
  Result := FALSE;
  hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
  if hSnap <> INVALID_HANDLE_VALUE then
  begin
    THR32.dwSize := SizeOf(THR32);
    Thread32First(hSnap, THR32);
    repeat
      if THR32.th32OwnerProcessID = PID then
      begin
        hOpen := OpenThread($0002, FALSE, THR32.th32ThreadID);
        if hOpen <> INVALID_HANDLE_VALUE then
        begin
          Result := TRUE;
          SuspendThread(hOpen);
          CloseHandle(hOpen);
        end;
      end;
    until Thread32Next(hSnap, THR32) = FALSE;
    CloseHandle(hSnap);
  end;
end;