코딩하는 나귀

function InjectDll(PID:DWORD; sDll:string):Boolean;
var
hLib:     Pointer;
hThread:  THandle;
pMod:     Pointer;
hOpen:    THandle;
dWritten: Cardinal;
ThreadID: Cardinal;
begin
  Result := FALSE;
  hOpen := OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
  if hOpen <> INVALID_HANDLE_VALUE then
  begin
    hLib := GetProcAddress(GetModuleHandle(PChar('kernel32.dll')), PChar('LoadLibraryA'));
    pMod := VirtualAllocEx(hOpen, nil, Length(sDll) + 1, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if WriteProcessMemory(hOpen, pMod, @sDll[1], Length(sDll), dWritten) then
      Result := TRUE;
    hThread := CreateRemoteThread(hOpen, nil, 0, hLib, pMod, 0, ThreadID);
    WaitForSingleObject(hThread, INFINITE);
    CloseHandle(hOpen);
    CloseHandle(hThread);
  end;
end;

function UnInjectDll(PID:DWORD; sDll:string):Boolean;
var
hSnap:  THandle;
MOD32:  MODULEENTRY32;
hLib:   Pointer;
hOpen:    THandle;
hThread:  THandle;
ThreadID: Cardinal;
begin
  Result := FALSE;
  hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PID);
  if hSnap <> INVALID_HANDLE_VALUE then
  begin
    MOD32.dwSize := SizeOf(MOD32);
    Module32First(hSnap, MOD32);
    repeat
      if MOD32.szExePath = sDll then
      begin
        hOpen := OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);
        if hOpen <> INVALID_HANDLE_VALUE then
        begin
          Result := TRUE;
          hLib := GetProcAddress(GetModuleHandle(PChar('kernel32.dll')), PChar('FreeLibrary'));
          hThread := CreateRemoteThread(hOpen, nil, 0, hLib, MOD32.modBaseAddr, 0, ThreadID);
          CloseHandle(hOpen);
          CloseHandle(hThread);
        end;
      end;
    until Module32Next(hSnap, MOD32) = FALSE;
  CloseHandle(hSnap);
  end;
end;