我有一个编译为 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/