0

我想使用Process32FirstW,但ERROR_BAD_LENGTH我打电话时得到GetLastError。使用tlhelp32似乎有效,但我想知道我在这里做错了什么:

program Project1;

{$APPTYPE CONSOLE}

uses
  Windows;

type
  PROCESSENTRY32W = record
    dwSize: Cardinal;
    cntUsage: Cardinal;
    th32ProcessID: Cardinal;       // this process
    th32DefaultHeapID: Pointer;
    th32ModuleID: Cardinal;        // associated exe
    cntThreads: Cardinal;
    th32ParentProcessID: Cardinal; // this process's parent process
    pcPriClassBase: Longint;    // Base priority of process's threads
    dwFlags: Cardinal;
    szExeFile: array[0..MAX_PATH - 1] of WideChar;// Path
  end;

function Process32NextW           (hSnapshot: Cardinal; var lppe: PROCESSENTRY32W): LongBool; external 'kernel32';
function Process32FirstW          (hSnapshot: Cardinal; var lppe: PROCESSENTRY32W): LongBool; external 'kernel32';
function CreateToolhelp32Snapshot (dwFlags, th32ProcessID: Cardinal): Cardinal; external 'kernel32';

function GetParentPID : Cardinal;
var
  HandleSnapShot    : Cardinal;
  EntryParentProc   : PROCESSENTRY32W;
  CurrentProcessId  : Cardinal;
begin
  result          := 0;
  HandleSnapShot  := CreateToolhelp32Snapshot($00000002, 0);
  if HandleSnapShot <> Cardinal(-1) then begin
    EntryParentProc.dwSize := SizeOf(PROCESSENTRY32W);
    if Process32FirstW(HandleSnapShot, EntryParentProc) then begin
      CurrentProcessId := GetCurrentProcessId;
      repeat
        if EntryParentProc.th32ProcessID = CurrentProcessId then begin
          result := EntryParentProc.th32ParentProcessID;
          break;
        end;
      until not Process32NextW(HandleSnapShot, EntryParentProc);
    end else begin
      writeln(GetLastError);
    end;
    CloseHandle(HandleSnapShot);
  end;
end;

begin
  writeln (GetParentPID);
  readln;
end.
4

1 回答 1

5

函数 Process32NextW (hSnapshot: Cardinal; var lppe: PROCESSENTRY32W): LongBool; 标准调用;外部“内核32”;

你省略了stdcall;。调用约定很重要,如果丢失了这个词,您的代码会错误地调用 API,从而导致您无法预料的结果。所以,你必须在那里小心。

于 2013-09-03T12:26:12.210 回答