使用C ++在Chrome中获取有效的标签网址

时间:2018-01-29 15:07:20

标签: c++ google-chrome winapi

several answered questions about this on stackoverflow,但它们似乎已过时且不再有效。 Chrome已changed its structure entirely。如果我尝试AccessibleObjectFromEvent技术,那么我只获得accName和accValue的NULL值。似乎there are solutions for python,但我找不到任何C ++解决方案。如何在C ++中检索活动的Tab URL?

1 个答案:

答案 0 :(得分:5)

使用Window SDK中的MDN工具,我们可以获取Chrome浏览器网址编辑框的属性名称:

Name:           "Address and search bar" *
ControlType:    UIA_EditControlTypeId (0xC354)

要在Chrome中找到有效标签,请使用FindWindowEx查找桌面上第一个可见的Chrome子窗口。

然后使用Inspect查找具有该ID的编辑控件。或者只是在Chrome中找到第一个编辑控件。

以下示例使用ATL COM类,它需要Visual Studio

#define UNICODE
#include <Windows.h>
#include <AtlBase.h>
#include <AtlCom.h>
#include <UIAutomation.h>

int main()
{
    CoInitialize(NULL);
    HWND hwnd = NULL;
    while(true)
    {
        hwnd = FindWindowEx(0, hwnd, L"Chrome_WidgetWin_1", NULL);
        if(!hwnd)
            break;
        if(!IsWindowVisible(hwnd))
            continue;

        CComQIPtr<IUIAutomation> uia;
        if(FAILED(uia.CoCreateInstance(CLSID_CUIAutomation)) || !uia)
            break;

        CComPtr<IUIAutomationElement> root;
        if(FAILED(uia->ElementFromHandle(hwnd, &root)) || !root)
            break;

        CComPtr<IUIAutomationCondition> condition;

        //URL's id is 0xC354, or use UIA_EditControlTypeId for 1st edit box
        uia->CreatePropertyCondition(UIA_ControlTypePropertyId, 
                CComVariant(0xC354), &condition);

        //or use edit control's name instead
        //uia->CreatePropertyCondition(UIA_NamePropertyId, 
        //      CComVariant(L"Address and search bar"), &condition);

        CComPtr<IUIAutomationElement> edit;
        if(FAILED(root->FindFirst(TreeScope_Descendants, condition, &edit))
            || !edit)
            continue; //maybe we don't have the right tab, continue...

        CComVariant url;
        edit->GetCurrentPropertyValue(UIA_ValueValuePropertyId, &url);
        MessageBox(0, url.bstrVal, 0, 0);
        break;
    }
    CoUninitialize();
    return 0;
}

对于非英语系统,"Address and search bar"可能有不同的名称