簡體   English   中英

如何將現有的HTML文件加載到CHtmlEditCtrl或導航到HTML文件?

[英]How can I load an existing HTML file into a CHtmlEditCtrl or navigate to the HTML file?

如何將現有的HTML文件加載到CHtmlEditCtrl或導航到HTML文件?

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

這是有關如何將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://...加載本地文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM