PowerShell如何通过任意窗口句柄获取对应进程 无需依赖第三方工具
PowerShell 获取任意活动窗口(含子窗口)所属进程的解决方案
原有代码仅通过
MainWindowHandle筛选进程,无法匹配同进程的子窗口句柄,导致无法返回正确进程。
无需遍历进程所有句柄,直接调用系统原生Win32 API即可实现需求,无任何外部工具依赖,方案如下:
完整实现代码
# 声明需要调用的User32.dll系统API Add-Type @" using System; using System.Runtime.InteropServices; public class User32 { // 获取当前活动窗口句柄 [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); // 通过窗口句柄获取所属进程ID [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); } "@ # 取当前活动窗口句柄 $activeHandle = [User32]::GetForegroundWindow() $processId = 0 # 调用API获取窗口对应进程ID [User32]::GetWindowThreadProcessId($activeHandle, [ref]$processId) # 直接获取目标进程对象 $targetProcess = Get-Process -Id $processId
方案优势
- 仅调用Windows系统原生接口,不需要安装WASP等任何外部工具
- 执行效率高,不需要遍历所有进程的所有窗口句柄做匹配
- 覆盖所有窗口类型:主窗口、子窗口、模态弹出框、右键菜单等所有活动窗口都能准确匹配到所属进程
内容的提问来源于stack exchange,提问作者Ephebopus
相关产品推荐
相关产品推荐

