【问题标题】:Not getting path of various system processes by GetModuleFileNameEx()没有通过 GetModuleFileNameEx() 获取各种系统进程的路径
【发布时间】:2011-07-21 05:35:14
【问题描述】:

我已经创建了这个函数来获取各种网络进程的路径,比如svchost、Firefox等。代码如下:

function GetProcessPath(var pId:Integer):String;
var
    Handle: THandle;

begin
    Result := '';
    try
        Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, pID);
        if Handle <> 0 then
        begin
            try
               SetLength(Result, MAX_PATH);
               if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
                   SetLength(Result, StrLen(PChar(Result)))
               else
                  Result := '';
            finally
                CloseHandle(Handle);
        end;
    end;

    except
       on E:Exception do
           ShowMessage(E.ClassName + ':' + E.Message);
    end;
end;

我的问题是我没有得到所有进程的路径。它适用于获取 Firefox 的路径以及其他类似的用户级进程。但是对于像alg、Svchost这样的进程,我无法通过这种方法获取路径。我的猜测是我必须使用一些不同的 API。我该如何解决这个问题?

我使用的是 Windows XP,32 位。

【问题讨论】:

    标签: delphi


    【解决方案1】:

    您需要设置调试权限。以下是它的完成方式:

    function NTSetPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
    var
      hToken: THandle;
      TokenPriv: TOKEN_PRIVILEGES;
      PrevTokenPriv: TOKEN_PRIVILEGES;
      ReturnLength: Cardinal;
    begin
      Result := True;
    
      // Only for Windows NT/2000/XP and later.
      if not (Win32Platform = VER_PLATFORM_WIN32_NT) then Exit;
    
      Result := False;
    
      // Obtain the processes token
      if OpenProcessToken(GetCurrentProcess(),
        TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
      begin
        try
          // Get the locally unique identifier (LUID) .
          if LookupPrivilegeValue(nil, PChar(sPrivilege),
            TokenPriv.Privileges[0].Luid) then
          begin
            TokenPriv.PrivilegeCount := 1; // One privilege to set
    
            case bEnabled of
              True: TokenPriv.Privileges[0].Attributes  := SE_PRIVILEGE_ENABLED;
              False: TokenPriv.Privileges[0].Attributes := 0;
            end;
    
            ReturnLength := 0; // Replaces a var parameter
            PrevTokenPriv := TokenPriv;
    
            // Enable or disable the privilege
    
            AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv),
              PrevTokenPriv, ReturnLength);
          end;
        finally
          CloseHandle(hToken);
        end;
      end;
    end;
    
    NtSetPrivilege('SeDebugPrivilege', TRUE); // Call this on form create
    

    【讨论】:

    • +1 @CyprUS 如果您打算支持 Vista 或更高版本,请注意 UAC 问题。
    猜你喜欢
    • 2014-10-25
    • 2014-04-12
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2016-08-04
    • 2020-06-28
    相关资源
    最近更新 更多