Thema: Delphi Das Handle ist ungültig

Einzelnen Beitrag anzeigen

TiGü

Registriert seit: 6. Apr 2011
Ort: Berlin
3.060 Beiträge
 
Delphi 10.4 Sydney
 
#4

AW: Das Handle ist ungültig

  Alt 2. Mai 2018, 10:25
Versuch mal anstatt GetModuleBaseName die Funktion GetProcessImageFileNameW.

Beispiel:
Delphi-Quellcode:
program Project3;

{$APPTYPE CONSOLE}

{$R *.res}


uses
  System.SysUtils,
  Winapi.Windows,
  PsAPI;

function GetProcessImageFileNameW(hProcess: THandle; lpBaseName: LPCWSTR; nSize: DWORD): DWORD; stdcall; external 'PSAPI.dll';

function GetBaseNameFromPID(const PID: DWORD): string;
var
  hProcess: THandle;
  LModule: HMODULE;
  path: array [0 .. MAX_PATH - 1] of WideChar;
  ErrorTxt: array [0 .. 500] of WideChar;
begin

  hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, PID);
  if hProcess <> 0 then
    try
      LModule := 0;
      path := '';
      // if GetModuleBaseName(hProcess, LModule, path, MAX_PATH) = 0 then
      if GetProcessImageFileNameW(hProcess, path, MAX_PATH) = 0 then
      begin
        ErrorTxt := '';
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, GetLastError, 0, ErrorTxt, 500, nil);
        Writeln(ErrorTxt);
        // RaiseLastOSError;
      end;
      Result := path;
    finally
      CloseHandle(hProcess)
    end
  else
    RaiseLastOSError;
end;

var
  gPID: DWORD;
  gName: string;

begin
  try
    while True do
    begin
      Writeln('Bitte PID eingeben');
      Readln(gPID);
      gName := GetBaseNameFromPID(gPID);
      Writeln(gName);
    end;
  except
    on E: Exception do
    begin
      Writeln(E.ClassName, ': ', E.Message);
      Readln;
    end;
  end;

end.
  Mit Zitat antworten Zitat