简体   繁体   English

如何获取当前活动应用程序窗口的路径?

[英]How to get path of current active application window?

I want to get the path to the executable file of the current active Window. 我想获取当前活动窗口的可执行文件的路径。

I tried: 我试过了:

var
  WindowModuleFileName : array[0..100] of Char;  
  sourceWindow: Hwnd;      
begin
  sourceWindow := GetActiveWindow;
  GetWindowModuleFileName(sourceWindow, PChar(WindowModuleFileName), sizeof(WindowModuleFileName));    
  ShowMessage(WindowModuleFileName);    
end;

But it returned correct answer only when my application window was active. 但是只有当我的应用程序窗口处于活动状态时,它才返回正确答案。 What am I doing wrong? 我究竟做错了什么?

You can't use GetWindowModuleFileName to locate files for other processes than your own, as stated on GetModuleFileName MSDN : GetModuleFileName MSDN上所述,您不能使用GetWindowModuleFileName来查找您自己进程以外的其他进程的文件:

Retrieves the fully-qualified path for the file that contains the specified module. 检索包含指定模块的文件的标准路径。 The module must have been loaded by the current process. 该模块必须已被当前进程加载。

To locate the file for a module that was loaded by another process, use the GetModuleFileNameEx function. 要查找由另一个进程加载的模块的文件,请使用GetModuleFileNameEx函数。

Therefore, you have to use GetModuleFileNameEx combined with GetWindowThreadProcessId / GetForegroundWindow . 因此,您必须将GetModuleFileNameExGetWindowThreadProcessId / GetForegroundWindow结合使用。 This will return you what you need: 这将返回您所需的内容:

uses
  Winapi.Windows, Winapi.PsAPI, System.SysUtils;

function GetCurrentActiveProcessPath: String;
var
  pid     : DWORD;
  hProcess: THandle;
  path    : array[0..4095] of Char;
begin
  GetWindowThreadProcessId(GetForegroundWindow, pid);

  hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, FALSE, pid);
  if hProcess <> 0 then
    try
      if GetModuleFileNameEx(hProcess, 0, @path[0], Length(path)) = 0 then
        RaiseLastOSError;

      result := path;
    finally
      CloseHandle(hProcess);
    end
  else
    RaiseLastOSError;
end;

GetActiveWindow gets the window handle to the active window that belongs to the calling thread only. GetActiveWindow将窗口句柄获取到仅属于调用线程的活动窗口。

You need to use GetForegroundWindow() function instead of GetActiveWindow() . 您需要使用GetForegroundWindow()函数而不是GetActiveWindow()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM