c# - 在 Windows x64 中从句柄获取可执行文件名

标签 c# 64-bit wow64 win32-process

我有一个编译为 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 位进程获取该信息?谢谢。 安德里亚

最佳答案

仅供引用,有一个 API GetWindowModuleFileName一次通话即可完成您想要的一切。不过,我还没有检查它在您的场景中是否效果更好。

关于c# - 在 Windows x64 中从句柄获取可执行文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1657823/

相关文章:

c# - ExecuteNonQuery() 抛出 "Incorrect syntax near the keyword ' 用户'”

c# - 使用数据绑定(bind)和线程关闭 WPF 应用程序

c# - "int"的大小是否在 x64 构建的应用程序上发生变化?

c# - 开发和调试内存占用 C# 应用程序

windows - 使用 32 位进程中的 64 位 COM 对象

C# 动态文件系统观察服务

c# - 循环优化或 lambda 闭合有问题?

wix - 产品的 x64 和 x86 版本之间的 WIX UpgradeCode 是否应该不同?

curl - Ubuntu 64bit 11.04 服务器和 curl 安装失败

c - 如何为 GetModuleFileNameEx 禁用 WOW64 文件系统重定向?