如何用Python或PowerShell获取桌面应用菜单文本实现自动化?
桌面应用菜单文本提取与自动化解决方案
Python 方案(基于pywinauto)
pywinauto是Windows桌面应用自动化的常用库,能直接定位控件并提取文本,比单纯模拟按键更可靠精准。
步骤与代码
- 安装依赖:
pip install pywinauto
- 核心实现代码:
from pywinauto import Application # 连接目标应用,支持窗口标题正则匹配或进程名 app = Application().connect(title_re="你的应用窗口标题.*") main_window = app.window(title_re="你的应用窗口标题.*") # 展开目标菜单(示例:打开"文件"菜单,替换为实际菜单路径) main_window.menu_select("文件") # 提取所有菜单项文本 menu_items = main_window.children(control_type="MenuItem") menu_texts = [item.window_text().strip() for item in menu_items if item.window_text().strip()] # 匹配并选择目标项 target_name = "你的目标工作表名称" if target_name in menu_texts: # 通过菜单路径直接选择,无需模拟按键 main_window.menu_select(f"文件->{target_name}")
补充说明
如果是右键菜单或点击触发的弹出菜单,可改用popup_menu()方法获取项:
# 示例:右键点击指定控件弹出菜单 popup_menu = main_window.child_window(title="目标控件").click_input(button="right") menu_texts = [item.text() for item in popup_menu.items()]
PowerShell 方案
PowerShell可通过AutoIt模块或原生.NET API实现菜单文本提取,以下两种方式可选:
方式一:AutoIt模块(简单易用)
- 安装模块:
Install-Module -Name AutoIt -Scope CurrentUser
- 核心实现代码:
Import-Module AutoIt # 获取目标窗口句柄,替换为应用窗口标题 $window_handle = AutoIt::WinGetHandle("你的应用窗口标题") AutoIt::WinActivate($window_handle) # 触发菜单弹出(示例:Alt+F打开文件菜单) AutoIt::Send("%f") Start-Sleep -Milliseconds 500 # 遍历提取所有菜单项文本 $menu_texts = @() $index = 0 while ($true) { $text = AutoIt::ControlGetText($window_handle, "", "[CLASS:MenuItem;INSTANCE:$index]") if ([string]::IsNullOrWhiteSpace($text)) { break } $menu_texts += $text.Trim() $index++ } # 匹配并选择目标项 $target_name = "你的目标工作表名称" $target_index = $menu_texts.IndexOf($target_name) if ($target_index -ne -1) { AutoIt::Send("{DOWN $target_index}{ENTER}") }
方式二:原生.NET API(无需额外模块)
Add-Type @" using System; using System.Runtime.InteropServices; using System.Text; public class MenuHelper { [DllImport("user32.dll")] public static extern IntPtr GetMenu(IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetMenuItemCount(IntPtr hMenu); [DllImport("user32.dll")] public static extern bool GetMenuString(IntPtr hMenu, uint uItem, StringBuilder lpString, int nMaxCount, uint uFlags); public static string[] GetTopLevelMenuItems(IntPtr hWnd) { IntPtr menu_handle = GetMenu(hWnd); int item_count = GetMenuItemCount(menu_handle); string[] items = new string[item_count]; StringBuilder sb = new StringBuilder(256); for (uint i = 0; i < item_count; i++) { GetMenuString(menu_handle, i, sb, sb.Capacity, 0); items[i] = sb.ToString().Trim(); } return items; } } "@ # 获取应用主窗口句柄(替换为进程名) $process = Get-Process -Name "你的应用进程名" $menu_texts = [MenuHelper]::GetTopLevelMenuItems($process.MainWindowHandle) # 匹配后模拟操作 $target_name = "你的目标工作表名称" if ($menu_texts -contains $target_name) { [System.Windows.Forms.SendKeys]::SendWait("%f") # 打开对应菜单 Start-Sleep -Milliseconds 500 [System.Windows.Forms.SendKeys]::SendWait("$target_name{ENTER}") }
内容的提问来源于stack exchange,提问作者PythonKiddieScripterX
相关产品推荐
相关产品推荐

