我需要在聚焦窗口的文本框中检索插入符号的索引,如果有的话,可以使用UI Automation或Win32 API函数。我要强调的是,我并不是指x,y坐标,而是指文本框文本内的插入符号的索引。我怎样才能做到这一点?另请参见this类似问题。
您可以为此使用UI Automation,尤其是具有IUIAutomationTextPattern2方法的GetCaretRange界面。
这里是示例Consoleapp C ++代码,该代码连续运行并在鼠标下显示当前元素的插入符位置:
int main()
{
CoInitializeEx(NULL, COINIT_MULTITHREADED);
{
CComPtr<IUIAutomation> automation;
// make sure you use CLSID_CUIAutomation8, *not* CLSID_CUIAutomation
automation.CoCreateInstance(CLSID_CUIAutomation8);
do
{
POINT pt;
if (GetCursorPos(&pt))
{
CComPtr<IUIAutomationElement> element;
automation->ElementFromPoint(pt, &element);
if (element)
{
CComBSTR name;
element->get_CurrentName(&name);
wprintf(L"Watched element %s\n", name);
CComPtr<IUIAutomationTextPattern2> text;
HRESULT hr = element->GetCurrentPatternAs(UIA_TextPattern2Id, IID_PPV_ARGS(&text));
if (text)
{
// get document range
CComPtr<IUIAutomationTextRange> documentRange;
text->get_DocumentRange(&documentRange);
// get caret range
BOOL active = FALSE;
CComPtr<IUIAutomationTextRange> range;
text->GetCaretRange(&active, &range);
if (range)
{
// compare caret start with document start
int caretPos = 0;
range->CompareEndpoints(TextPatternRangeEndpoint_Start, documentRange, TextPatternRangeEndpoint_Start, &caretPos);
wprintf(L" caret is at %i\n", caretPos);
}
}
}
}
Sleep(500);
} while (TRUE);
}
CoUninitialize();
return 0;
}
技巧是使用IUIAutomationTextRange::CompareEndpoints方法,该方法允许您将插入符号范围与另一个范围(例如整个文档范围)进行比较。
注意有缺点: