I am doing a simple QueryInterface()
to get the IHTMLElement2
interface, but it always fails with E_NOINTERFACE
.
UPDATE: I need to get the IHTMLElement2
interface of the body
element because it has a focus()
method so I can set focus to the body. It can't be done with the IHTMLElement
interface.
Any ideas why this errors (or how to reach 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();
}
}
I've reached my own solution how to reach body->focus()
which follows:
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();
}
}
}
}
EDIT (suggested by Reby Lebeau) - simplified version:
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();
}
}
}