如何检测UWP应用运行?解决WinWait ahk_exe onenoteim.exe无效问题
检测UWP应用运行状态 & 精确定位OneNote UWP窗口
针对你遇到的两个问题——检测UWP应用是否运行,以及准确定位OneNote UWP窗口而不触发其他同名窗口,我给你整理了具体的解决方案:
一、检测UWP应用是否在运行
UWP应用基于包模型,不能仅靠进程名判断(很多UWP窗口的进程是ApplicationFrameHost.exe),最可靠的方式是通过包家族名来查询。以OneNote UWP为例,它的包家族名是Microsoft.Office.OneNote_8wekyb3d8bbwe(你可以在PowerShell中执行Get-AppxPackage *OneNote*确认)。
在AutoHotkey中实现检测
你可以封装一个函数,调用PowerShell查询对应包的运行进程:
IsUWPRunning(packageFamilyName) { shell := ComObjCreate("WScript.Shell") cmd := "powershell -Command ""Get-Process | Where-Object {$_.PackageFamilyName -eq '" packageFamilyName "'} | Select-Object -First 1""" output := shell.Exec(cmd).StdOut.ReadAll() return output != "" } ; 使用示例:检测OneNote UWP是否运行 if (IsUWPRunning("Microsoft.Office.OneNote_8wekyb3d8bbwe")) { MsgBox, OneNote UWP正在运行! } else { MsgBox, OneNote UWP未运行! }
二、精确定位OneNote UWP窗口(避免触发其他OneNote窗口)
你之前用WinWait ahk_exe onenoteim.exe无效,是因为OneNote UWP的主窗口属于ApplicationFrameHost.exe进程,而非onenoteim.exe(后者是辅助进程)。要精准定位,需要结合窗口句柄+包家族名来筛选:
AutoHotkey实现精确查找
下面的代码会遍历所有ApplicationFrameHost.exe的窗口,通过Windows API获取每个窗口对应进程的包家族名,匹配OneNote UWP的包名后返回窗口句柄:
; 获取窗口对应进程的包家族名 GetWindowPackageFamilyName(hwnd) { if !DllCall("GetWindowThreadProcessId", "Ptr", hwnd, "PtrP", pid) return "" ; 打开进程(需要查询权限) hProcess := DllCall("OpenProcess", "UInt", 0x400 | 0x10, "Int", 0, "UInt", pid, "Ptr") if !hProcess return "" ; 先获取所需缓冲区大小 varCapacity := 0 DllCall("GetPackageFamilyName", "Ptr", hProcess, "UIntP", varCapacity, "Ptr", 0) ; 分配缓冲区并获取包家族名 buf := VarSetCapacity(buf, varCapacity * 2, 0) success := DllCall("GetPackageFamilyName", "Ptr", hProcess, "UIntP", varCapacity, "Str", buf) DllCall("CloseHandle", "Ptr", hProcess) return success ? StrGet(&buf, "UTF-16") : "" } ; 查找OneNote UWP的窗口句柄 FindOneNoteUWPHwnd() { ; 获取所有ApplicationFrameHost的窗口 WinGet, hwnds, List, ahk_class ApplicationFrameWindow ahk_exe ApplicationFrameHost.exe Loop, %hwnds% { hwnd := hwnds%A_Index% pkgFamily := GetWindowPackageFamilyName(hwnd) ; 匹配OneNote UWP的包家族名 if (pkgFamily = "Microsoft.Office.OneNote_8wekyb3d8bbwe") { return hwnd } } return 0 ; 未找到返回0 } ; 使用示例:等待并激活OneNote UWP窗口 Loop { hwnd := FindOneNoteUWPHwnd() if (hwnd) { WinActivate, ahk_id %hwnd% break } Sleep, 500 ; 每0.5秒检查一次 }
这个方法完全基于UWP应用的唯一标识(包家族名),不会误触发桌面版OneNote或其他含"OneNote"标题的窗口。
内容的提问来源于stack exchange,提问作者CodeSharpMarvin
相关产品推荐
相关产品推荐

