如何在MFC编程中使用GetDHtmlDocument()

How to use GetDHtmlDocument() in MFC programming?

本文关键字:GetDHtmlDocument MFC 编程      更新时间:2023-10-16

我正在尝试使用

HRESULTGetDHtmlDocument (IHTMLDocument2* * pphtmlDoc);

函数。

基本上,我试图呈现GUI在一个HTML视图对话框应用程序(c++ w/MFC)给定不同的配置(加载输入)。

所以我把下面的代码在OnInitDialog()函数。

BOOL CSampleProgramDlg::OnInitDialog()
{
    CDHtmlDialog::OnInitDialog();
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);
    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }
    SetIcon(m_hIcon, TRUE); 
    SetIcon(m_hIcon, FALSE);
    // My code starts from here....
    HRESULT hr = S_OK;
    IHTMLDocument2 *pphtmlDoc;
    //MessageBox(_T("If I let this MessageBox to pop-up, the code works fine."));
    hr = GetDHtmlDocument(&pphtmlDoc);
    IHTMLElement *e;
    hr = GetElement(_T("someElement"), &e);
    if (SUCCEEDED(hr))
        e->put_innerHTML(_T("<h1>someLoadingInputWillGoHereLater</h1>"));
    //My code ends here.....
    return TRUE;
}

正如我在上面代码中注释的那样,如果我让消息框弹出ID="someElement"的元素将打印出" someeloadinginputwillgoherelater "。

但是如果我注释掉Messagebox, GetDHtmlDocument()返回"E_NOINTERFACE" HRESULT,并且它使代码不工作。

我只能猜测可能是"焦点"的问题。但是我不能找出确切的原因。

所以我请求你的帮助。= (

调用GetDHtmlDocument()GetElement()将返回E_NOINTERFACE

据我所知,你是不是总是保证有html文档完全加载时,你在CDHtmlDialog::OnInitDialog()执行。

相反,您应该在CSampleProgramDlg中重写CDHtmlDialog::OnDocumentComplete()。它是一个回调函数会在文档被加载时被调用。你到时可以评估文件。
void CSampleProgramDlg::OnDocumentComplete(
   LPDISPATCH pDisp,
   LPCTSTR szUrl 
)
{
    // You can get the document and elements here safely
}

MessageBox()的调用可能会以某种方式触发文档提前加载。虽然我不是百分之百肯定。

希望对你有帮助。