天天看点

在对话框中使用CHtmlView类打开网页

为了在对话框中显示HTML文件,必须将CHtmlCtrl类与对话框中的一个静态控制(也可以是其它控制)关联起来,这样才能为显示HTML文件提供一个窗口,为此可以在CHtmlCtrl类中定义一个创建函数:

BOOL CHTMLCtrl::CreateFromStatic(CStatic* pStaticWnd, CWnd* pParent) 

    ASSERT(NULL!=pStaticWnd && NULL!=pStaticWnd->GetSafeHwnd()); 

    ASSERT(NULL!=pParent && NULL!=pParent->GetSafeHwnd()); 

    CRect rc; 

    pStaticWnd->GetClientRect(&rc); 

    int nID = pStaticWnd->GetDlgCtrlID(); 

    LPCTSTR lpClassName = AfxRegisterWndClass(NULL); 

    return Create(lpClassName, _T(""), WS_CHILD|WS_VISIBLE, rc, pParent, nID, NULL); 

注意观察nID是必须的.

重载这个函数(必须),这是避免主控程序将CHtmlView对象看作是文档/视图框架:

int CHTMLCtrl::OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message) 

    // TODO: Add your message handler code here and/or call default 

    return CWnd::OnMouseActivate(pDesktopWnd, nHitTest, message); 

//Do not call it. 

    // return CHtmlView::OnMouseActivate(pDesktopWnd, nHitTest, message); 

然后在对话框中可以这样调用:

BOOL CHomePage::OnInitDialog() 

    CDialog::OnInitDialog(); 

    GetClientRect(&rc); 

    CStatic* pStatic = (CStatic*)GetDlgItem(IDC_STATIC_HTML); 

    pStatic->MoveWindow(&rc); 

    m_pHTMLPage = new CHTMLCtrl; 

    CHTMLCtrl* pHTMLCtrl = (CHTMLCtrl*)m_pHTMLPage; 

    pHTMLCtrl->CreateFromStatic(pStatic, this); 

    pHTMLCtrl->Navigate(_T("http://www.osssk1.com")); 

    return TRUE; 

另外,函数Navigate不但支持URL,还可以打开一个本地html文件,只是要指定具体的路径.

函数CHTMLCtrl::OnNavigateError(...DWORD dwError...)有一个指出打开URL是否正确的参数dwError,如果它的值不是200,证明是错误的,此时不需要再向下执行,而是转而打开本地html文件.需要注意的是,打开本地文件应该从父窗口打开,而不是该类对象自己的行为.所以这里向父窗口发送一个消息(异步发送).

void CHTMLCtrl::OnNavigateError(LPCTSTR lpszURL, LPCTSTR lpszFrame, 

DWORD dwError,BOOL *pbCancel) 

    if (200!=dwError && 0==_tcscmp(_T("http://www.osssk1.com/"), lpszURL)) 

    { 

        // Navigate to local html file. 

        GetParent()->PostMessage(WM_NAVI_LOCAL_URL, 0, 0); 

        return; 

    } 

    return CHtmlView::OnNavigateError(lpszURL, lpszFrame, dwError, pbCancel); 

父窗口接收到该消息就知道打开URL失败,应该打开本地html文件.

BOOL CHomePage::OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult) 

    // TODO: Add your specialized code here and/or call the base class 

    if (WM_NAVI_LOCAL_URL == message) 

        CHTMLCtrl* pHTMLCtrl = (CHTMLCtrl*)m_pHTMLPage; 

        pHTMLCtrl->Navigate(_T("e:\\index.html")); 

        return TRUE; 

    return CDialog::OnWndMsg(message, wParam, lParam, pResult); 

本文转自jetyi51CTO博客,原文链接:http://blog.51cto.com/jetyi/1073361 ,如需转载请自行联系原作者

继续阅读