如何将现有HTML文件加载到CHtmlEditCtrl或导航到HTML文件?

时间:2011-11-22 09:39:52

标签: c++ mfc

如何将现有HTML文件加载到CHtmlEditCtrl或导航到HTML文件?

2 个答案:

答案 0 :(得分:0)

以下是如何将html字符串加载到CHtmlView

的示例
void CMyHtmlView::Clear()
{ 
    if(!IsWindow(m_hWnd))
        return;

    IHTMLDocument2* pDoc = GetDocument();

    if(!pDoc)
    {
        Navigate2("about:blank");
        return;
    }

    pDoc->close();

    VARIANT    open_name;
    VARIANT    open_features;
    VARIANT    open_replace;
    IDispatch *open_window = NULL;

    ::VariantInit(&open_name);

    open_name.vt      = VT_BSTR;
    open_name.bstrVal = ::SysAllocString(L"_self");

    ::VariantInit(&open_features);
    ::VariantInit(&open_replace);

    HRESULT hr = pDoc->open(::SysAllocString(L"text/html"),open_name,open_features,
        open_replace,&open_window);

    if (hr == S_OK) 
        Refresh();

    if (open_window != NULL) 
        open_window->Release();

}

void CMyHtmlView::LoadHTML(const CString& html)
{
    if(!IsWindow(m_hWnd))
        return;

    Clear();

    IHTMLDocument2* pDoc = GetDocument();

    if(!pDoc)
        return;

    SAFEARRAY* sa = SafeArrayCreateVector(VT_VARIANT,0,1);
    VARIANT* var;

    SafeArrayAccessData(sa,(LPVOID*) &var);
    var->vt = VT_BSTR;
    var->bstrVal = html.AllocSysString();
    SafeArrayUnaccessData(sa);

    pDoc->write(sa);
    pDoc->Release();
}

IHTMLDocument2* CMyHtmlView::GetDocument()
{
    IHTMLDocument2* document = NULL;

    if (m_pBrowser != NULL) 
    {
        IDispatch *document_dispatch = NULL;
        HRESULT hr = m_pBrowser->get_Document(&document_dispatch);

        if (SUCCEEDED(hr) && (document_dispatch != NULL)) 
        {
            hr = document_dispatch->QueryInterface(IID_IHTMLDocument2,(void **)&document);                
            document_dispatch->Release();
        }
    }

    return document;
}

我还没试过,但我想用file://...而不是http://...加载本地文件会有效。

答案 1 :(得分:0)

使用Navigate或Navigate2方法之一;

要访问在线页面:

pHtmlView->Navigate("http://www.google.com");

要访问本地HTML文件:

pHtmlView->Navigate("c:\\mypath\\myfile.html");

根据您的实现,HTML控件可能需要COM类型访问,或者如果您需要设置其他信息(如标题),那么;

CString strHeader = "User Agent:Mozilla/5.0...";
m_browserCtrl.Navigate2(&_variant_t(_T("file://C:\\mypath\\myfile.htm")), NULL, NULL, NULL, &_variant_t(_T(strHeader)));