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

Dyn*_*ope 2 c++ mfc focus dhtml hresult

我正在尝试使用

HRESULT GetDHtmlDocument(IHTMLDocument2**pphtmlDoc);

在MFC编程中的功能.

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

所以我将以下代码放在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;
}
Run Code Online (Sandbox Code Playgroud)

正如我在上面的代码中注释的那样,如果我让Messagebox弹出ID ="someElement"的元素将打印出"someLoadingInputWillGoHereLater".

但是如果我注释掉Messagebox,GetDHtmlDocument()会返回"E_NOINTERFACE"HRESULT,这会使代码无效.

我只能猜测它可能是"焦点"问题.但是,我无法弄清楚具体原因.

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

Eri*_*c Z 6

您能打电话GetDHtmlDocument()GetElement()返回E_NOINTERFACE.

根据我的知识,你并不总是保证在你表演时完全加载html文件CDHtmlDialog::OnInitDialog().

相反,你应该重写CDHtmlDialog::OnDocumentComplete()CSampleProgramDlg.它是一个回调函数,在加载文档时会被调用.然后,您可以评估该文档.

void CSampleProgramDlg::OnDocumentComplete(
   LPDISPATCH pDisp,
   LPCTSTR szUrl 
)
{
    // You can get the document and elements here safely
}
Run Code Online (Sandbox Code Playgroud)

您的呼叫MessageBox()可能会以某种方式触发文档提前加载.虽然我不是百分百肯定的.

希望有所帮助.

  • 我注意到甚至等待m_pBrowserApp-> get_ReadyState(&result); 获取"READYSTATE_COMPLETE"并不能保证所有元素都可用.谢谢你的方法. (2认同)