首页 > 解决方案 > 单击按钮或在文本框中键入时检索元素名称和 xpath

问题描述

我想开发一个应用程序来帮助我记录在特定 Windows 应用程序(例如 Microsoft Excel、Acrobat、记事本等)中执行的所有键盘和鼠标事件。

到目前为止,我尝试了 Pyhook 和 Win32gui 来实现我的目标。但是,我不知道如何检索以下信息:

非常感谢您的帮助或建议,如果我写错了,请原谅我。我对 Python 很陌生;)

标签: pythonwinapiwin32guipyhook

解决方案


首先获取当前鼠标点击位置,用于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)

推荐阅读