如何解决如何获取具有键盘焦点的文本框的值?
我想检索用户正在输入的文本框的值
到目前为止,我已经得到了这段代码,它输出了我的键盘焦点所在的元素中所写的内容。 但是,它仅适用于记事本的文本区域,当我尝试在其他应用程序上使用它时,它会打印“Chrome Legacy Window”之类的内容
from ctypes import windll,create_unicode_buffer
import win32gui
import win32con
import time
def getForegroundWindowTitle():
hWnd = windll.user32.GetForegroundWindow()
length = windll.user32.GetWindowTextLengthW(hWnd)
buf = create_unicode_buffer(length + 1)
windll.user32.GetWindowTextW(hWnd,buf,length + 1)
if buf.value:
return buf.value
else:
return None
time.sleep(3)
windowHandle = win32gui.FindWindow(None,getForegroundWindowTitle())
childwindowHandle = win32gui.FindWindowEx(windowHandle,None,win32gui.GetFocus(),None)
buff = create_unicode_buffer(4096)
win32gui.SendMessage(childwindowHandle,win32con.WM_GETTEXT,4096,buff) #0x000D
print(buff.value)
解决方法
您可以使用 IUIAutomation::GetFocusedElement 检索具有输入焦点的当前 UI 自动化元素,然后获取值模式。
这是一个 C++ 的 win32 示例,你可以随意在 Python 中转换它:
#include <Windows.h>
#include <iostream>
#include <UIAutomation.h>
BOOL main()
{
HRESULT hr;
CoInitialize(0);
Sleep(2000);
IUIAutomation* pClientUIA;
hr = CoCreateInstance(CLSID_CUIAutomation,NULL,CLSCTX_INPROC_SERVER,IID_IUIAutomation,reinterpret_cast<void**>(&pClientUIA));
if (S_OK != hr)
{
printf("CoCreateInstance error: %d\n",GetLastError());
return FALSE;
}
IUIAutomationElement* pFocusedElement;
hr = pClientUIA->GetFocusedElement(&pFocusedElement);
if (S_OK != hr)
{
printf("GetFocusedElement error: %d\n",GetLastError());
return FALSE;
}
IValueProvider* pValueProvider;
hr = pFocusedElement->GetCurrentPattern(UIA_ValuePatternId,reinterpret_cast<IUnknown**> (&pValueProvider));
if (S_OK != hr)
{
printf("GetCurrentPattern error: %d\n",GetLastError());
return FALSE;
}
BSTR text;
hr = pValueProvider->get_Value(&text);
if (S_OK != hr)
{
printf("get_Value error: %d\n",GetLastError());
return FALSE;
}
wprintf(L"%s\n",text);
SysFreeString(text);
CoUninitialize();
}
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。