delphi - 如何从窗口句柄中获取可执行文件名?

标签 delphi winapi

我有这个代码:

procedure TForm1.Button1Click(Sender: TObject);
var
  MyHandle: THandle;
begin
  MyHandle:=FindWindow(nil, 'Delphi');
  SendMessage(MyHandle, WM_CLOSE, 0, 0);
 // Here will be a message like ' title found and it's test.exe that has 'Delphi' Title
end;

例如,test.exe 是具有 'Delphi' 标题的进程,我想通过以下方式获取该进程的 EXE 文件名使用窗口句柄。那可能吗?如果是这样,我可以做一些引用吗?

最佳答案

这是我使用的程序,您可能会在 Internet 的其他地方找到它。我不记得确切的来源,可能是 https://www.swissdelphicenter.ch .

uses
  Windows, TlHelp32, ...

function WindowHandleToEXEName(handle : THandle) : string;
var
  snap : THandle;
  pe : tagPROCESSENTRY32;
  pid : THandle;
  found : boolean;
begin
  Windows.SetLastError(ERROR_SUCCESS);

  result := '';
  if (handle = 0) then exit;

  snap := TLHelp32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (snap = Cardinal(-1)) then exit;

  Windows.GetWindowThreadProcessId(handle, @pid);
  pe.dwSize := Sizeof(pe);
  found := TLHelp32.Process32First(snap, pe);

  while found do
  begin
    if (pe.th32ProcessID = pid) then
    begin
      result := String(pe.szExeFile);
      break;
    end;
    found := TLHelp32.Process32Next(snap, pe);
  end;
  CloseHandle(snap);
end;

关于delphi - 如何从窗口句柄中获取可执行文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67151522/

相关文章:

delphi - 我如何使用 Lazarus 中 openSSL 模块中的 BIGNUM

winapi - 在 Windows 中等待孙子进程

c - 在子菜单项上使用 EnableMenuItem

c - 使用 Windows slim 读/写锁

c++ - 如何使用 ReadFile 修复乱码?

delphi - 使用Delphi中的十六进制内存值进行常量单

delphi - 长入字符串 - StrToInt() 安全吗?

delphi - 是否可以清除FPU?

delphi - Delphi 中枚举的所有项均为常量

Python 2.6 Win32 (xp) 上的 Python 多处理