【问题标题】:Getting executable file name from handle in Windows x64从 Windows x64 中的句柄获取可执行文件名
【发布时间】:2010-09-22 16:44:39
【问题描述】:

我有一个编译为 x86 的 c# 应用程序,因此它在 Windows 7 x64 上作为 32 位应用程序运行。 在应用程序运行时,我需要检测活动窗口的可执行文件名。 在 Winodws XP 上,以下代码运行良好(从活动窗口句柄获取进程文件名)。 在 x64 上,它只报告 32 位进程的名称(为其他进程返回垃圾,可能是因为我没有检查返回的数据)。我正在传递使用 GetForegroundWindow API 获得的活动窗口的句柄。

public static string GetProcessPathFromWindowHandle(IntPtr hWnd) {

        string filename = string.Empty;
        uint pid=0;
        Unmanaged.GetWindowThreadProcessId(hWnd, out pid);

        //error in Win64: returns strange characters for Win64 files
        const int nChars = 1024;
        StringBuilder filenameBuffer = new StringBuilder(nChars);
        IntPtr hProcess = Unmanaged.OpenProcess(1040, 0, pid);
        Unmanaged.GetModuleFileNameEx(hProcess, IntPtr.Zero, filenameBuffer, nChars);
        Unmanaged.CloseHandle(hProcess);

        filename = filenameBuffer.ToString();

        //Get the name of the Windows
        int length = Unmanaged.GetWindowTextLength(hWnd);
        StringBuilder sb = new StringBuilder(length + 1);
        Unmanaged.GetWindowText(hWnd, sb, sb.Capacity);

        Logger.Main.LogMessage("Window Title is: " + sb);
        Logger.Main.LogMessage("Process filename is: " + filename);
        return filename;
    }

我能否在 64 位环境中从 32 位进程中获取该信息?谢谢。 安德烈亚

【问题讨论】:

    标签: c# 64-bit wow64 win32-process


    【解决方案1】:

    仅供参考,有一个 API GetWindowModuleFileName 可以在一次调用中满足您的所有需求。不过,我还没有检查它是否在您的场景中效果更好。

    【讨论】:

      【解决方案2】:

      由于没有错误检查:您是否单步执行代码并验证GetModuleFileNameEx 之前的各种API 调用是否返回合理信息?此外,您应该定义一些符号常量,而不是硬编码 1040 访问说明符。

      您是否尝试过使用System.Diagnostics.Process.GetProcessById()?它有一个MainModule 属性,您可以从中获取FileName。不过值得一试。

      不过,一些粗略的谷歌搜索表明你可能会陷入 x64 与 WoW64 的墙。其中一个更有用的搜索结果是this - 摘要:查看QueryFullProcessImageName

      编辑:

      Apparently WMI 可以弥补 WoW64 的差距,让您可以做到SELECT ExecutablePath FROM Win32_Process WHERE ProcessID = %ProcessID%。根据我的经验,WMI 有点重,所以它是最后的手段。

      【讨论】:

      • 这个question 有一个使用GetProcessById + MainModule 获取文件名的例子。
      • 刚刚试了一下,还是得到了以下Win32Exception“A 32 bit processes cannot access modules of a 64 bit process.”
      猜你喜欢
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2010-09-16
      相关资源
      最近更新 更多