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

C++ 如何将现有HTML文件加载到CHtmlEditCtrl或导航到HTML文件?,c++,mfc,C++,Mfc,如何将现有HTML文件加载到CHtmlEditCtrl或导航到HTML文件?以下是如何将HTML字符串加载到CHtmlView的示例: void CMyHtmlView::Clear() { if(!IsWindow(m_hWnd)) return; IHTMLDocument2* pDoc = GetDocument(); if(!pDoc) { Navigate2("about:blank"); retur

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

以下是如何将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://...
将起作用。

使用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)));