TWebBrowser QueryInterface IID_IHTMLElement2 总是返回 E_NOINTERFACE

问题描述

我正在做一个简单的 QueryInterface()获取 IHTMLElement2 接口,但它总是以 E_NOINTERFACE 失败。

更新:我需要获取 IHTMLElement2 元素的 body 接口,因为它有一个 focus() 方法,因此我可以将焦点设置到正文。使用 IHTMLElement 接口无法做到这一点。

任何想法为什么会出现此错误(或如何到达 body->focus())?

Webbrowser1->Navigate(L"c:\\test.htm");
while (Webbrowser1->Busy) Application->ProcessMessages();

DelphiInterface<IHTMLDocument2> diDoc = Webbrowser1->Document;
if (diDoc) {
    DelphiInterface<IHTMLElement2> diBodyElement;

    // all good until this point
    if (SUCCEEDED(diDoc->QueryInterface(IID_IHTMLElement2,reinterpret_cast<void**>(&diBodyElement))) && diBodyElement) {
        // Never reaches this part - always E_NOINTERFACE when querying for IID_IHTMLElement2
        diBodyElement->focus();
        }
    }

解决方法

我已经找到了如何到达 body->focus() 的我自己的解决方案,如下所示:

DelphiInterface <IHTMLDocument2> diDoc2 = WebBrowser1->Document;

if (diDoc2) {
    DelphiInterface<IHTMLElement>     pBody1;
    DelphiInterface<IHTMLElement2>    pBody2;
    DelphiInterface<IHTMLBodyElement> pBodyElem;

    if (SUCCEEDED(diDoc2->get_body(&pBody1)) && pBody1) {
        if (SUCCEEDED(pBody1->QueryInterface(IID_IHTMLBodyElement,reinterpret_cast<void**>(&pBodyElem))) && pBodyElem) {
        if (SUCCEEDED(pBodyElem->QueryInterface(IID_IHTMLElement2,reinterpret_cast<void**>(&pBody2))) && pBody2) {
            pBody2->focus();
            }
        }
    }
}

编辑(Reby Lebeau 建议) - 简化版:

DelphiInterface <IHTMLDocument2> diDoc2 = WebBrowser1->Document;

if (diDoc2) {
    DelphiInterface<IHTMLElement>  pBody1;
    DelphiInterface<IHTMLElement2> pBody2;

    if (SUCCEEDED(diDoc2->get_body(&pBody1)) && pBody1) {
        if (SUCCEEDED(pBody1->QueryInterface(IID_IHTMLElement2,reinterpret_cast<void**>(&pBody2))) && pBody2) {
            // focus to <body> element
            pBody2->focus();
            }
        }
    }