如何将Native Messaging的--parent-window转为C# IntPtr并获取进程文件名
修复Chrome原生消息父窗口进程文件名获取代码
原代码的核心问题是错误地将十进制窗口句柄按十六进制解析,同时缺少必要的异常处理,导致无法正常运行。以下是修复后的完整代码:
using System; using System.Diagnostics; using System.Runtime.InteropServices; class NativeMessagingHelper { [DllImport("user32.dll", SetLastError = true)] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId); static void Main(string[] args) { foreach (string arg in args) { // 精确匹配参数格式,避免误判 if (arg.StartsWith("--parent-window=", StringComparison.OrdinalIgnoreCase)) { try { // 拆分参数值 string handleStr = arg.Substring("--parent-window=".Length); // 按十进制解析窗口句柄(Chrome传递的是十进制值) long handleValue = long.Parse(handleStr); IntPtr hwnd = new IntPtr(handleValue); uint pid; // 获取窗口所属进程ID uint threadId = GetWindowThreadProcessId(hwnd, out pid); if (threadId == 0 || pid == 0) { Console.WriteLine("无效的窗口句柄"); continue; } // 获取进程并输出主模块文件名 using (Process process = Process.GetProcessById((int)pid)) { // 处理64位系统下访问32位进程的情况 bool isProcess64Bit = !Environment.Is64BitOperatingSystem || process.Is64Bit; if (!isProcess64Bit && Environment.Is64BitOperatingSystem) { Console.WriteLine("无法在64位系统中获取32位进程的主模块信息"); continue; } Console.WriteLine(process.MainModule.FileName); } } catch (FormatException) { Console.WriteLine("窗口句柄格式无效"); } catch (ArgumentException ex) { Console.WriteLine($"进程不存在或无法访问: {ex.Message}"); } catch (InvalidOperationException ex) { Console.WriteLine($"无法获取进程信息: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"发生未知错误: {ex.Message}"); } } } } }
关键修复点说明
- 句柄解析修正:Chrome原生消息传递的
--parent-window参数值是十进制窗口句柄,因此使用long.Parse而非十六进制转换,同时用long类型适配64位系统的窗口句柄。 - 精确参数匹配:使用
StartsWith替代IndexOf,避免包含--parent-window子串的其他参数被误判。 - 异常处理:覆盖参数格式错误、无效窗口句柄、进程无法访问等常见场景,提高代码健壮性。
- 64位兼容性:处理64位系统中访问32位进程时无法获取主模块的问题。
内容的提问来源于stack exchange,提问作者Jeff Baker
相关产品推荐
相关产品推荐

