python - 单击按钮或在文本框中键入时检索元素名称和 xpath
问题描述
我想开发一个应用程序来帮助我记录在特定 Windows 应用程序(例如 Microsoft Excel、Acrobat、记事本等)中执行的所有键盘和鼠标事件。
到目前为止,我尝试了 Pyhook 和 Win32gui 来实现我的目标。但是,我不知道如何检索以下信息:
- 单击的目标元素名称或用户在其中编写内容的位置(例如,如果应用程序是记事本,我想在用户单击“格式”菜单时存储“格式”)
- 该目标元素名称的 Xpath(按照上面的示例,我想知道,对于该菜单格式,它的父句柄和相应的类父)
非常感谢您的帮助或建议,如果我写错了,请原谅我。我对 Python 很陌生;)
解决方案
首先获取当前鼠标点击位置,用于WindowFromPoint
获取当前窗口句柄;
GetClassName
获取窗口类名;
GetMenu
得到HMENU
句柄;
然后用于MenuItemFromPoint
获取菜单项ID(如果指定位置没有菜单项,此函数返回-1);
最后使用GetMenuItemInfo
(该GetMenuString
功能已被GetMenuItemInfo
) 获取菜单文本。
这是一个简单的 C++ 测试示例:
#include <Windows.h>
#include <iostream>
int main()
{
Sleep(2000);//give us the time to test clicking on the menu.
POINT p;
GetCursorPos(&p);
HWND h = WindowFromPoint(p);
char classname[100] = { 0 };
GetClassName(h, classname,100);
MENUBARINFO menubar = {0};
menubar.cbSize = sizeof(MENUBARINFO);
HMENU menu = GetMenu(h);
int id = MenuItemFromPoint(h, menu,p);
MENUITEMINFO info = { 0 };
info.cbSize = sizeof(MENUITEMINFO);
info.fMask = MIIM_STRING;
info.dwTypeData = NULL;
GetMenuItemInfo(menu, id , true,&info);
info.dwTypeData = (LPSTR)malloc(info.cch+1);
info.cch++;
GetMenuItemInfo(menu, id, true, &info);
MessageBox(NULL, info.dwTypeData,"Menu Name",0);
free(info.dwTypeData);
return 0;
}
更新:
那是我测试过的代码,对我有用。(在记事本中测试)
import win32api
import win32gui
import win32gui_struct
import win32con
import time
import ctypes
from ctypes.wintypes import tagPOINT
time.sleep(3) #point to the menu before the time ends.
pos = win32gui.GetCursorPos()
hwnd = win32gui.WindowFromPoint(pos)
##get ClassName
ClassName = win32gui.GetClassName(hwnd)
menu = win32gui.GetMenu(hwnd)
print("ClassName = " + ClassName)
##get Id
point = tagPOINT(pos[0],pos[1])
Id = ctypes.windll.user32.MenuItemFromPoint(hwnd,menu,point)
print("Id = " + str(Id))
##get Menu
info,extras = win32gui_struct.EmptyMENUITEMINFO(win32con.MIIM_STRING)
win32gui.GetMenuItemInfo(menu,Id,1,info)
strings = win32gui_struct.UnpackMENUITEMINFO(info)
print("Menu = " + strings.text)
推荐阅读
- flutter - 在颤动中找到现有用户时如何更改文本字段错误标签?
- ruby-on-rails - Rails 路由:如何重命名(嵌套)资源块中的 params-Hash 键?
- windows - 如何在 Windows 批处理文件中传递密码和 ssh 命令
- active-directory - ldap 查询获取 ACL
- c# - 使用附加到触发器的此脚本时出现 NullReferenceException
- python - 一次迭代numpy矩阵块
- java - WebClient 实现 - 执行这段代码“WebClient.builder().build()”时出现错误
- c++ - 将我的自定义编译器与乱序执行并行化
- python - 如何在 Matplotlib 中将方向均值叠加到 hexbin 图?
- javascript - 200 个字段/列的 MYSQL 过滤器