公司項目中一直存在着一個CHtmlView模塊來顯示URL,但是隨着web頁面的更新(加入HTML5 and 其它一些比較新的技術)越來越發現使用CHtmlView已經無法滿足目前的需求。開始還是試着去修改一些東西去滿足當前需要,不過好景不長終於有一天CHtmlView連我們目前的web頁面都打不開了,於是決定採用Chrome來作爲瀏覽器引擎。
嵌入到MFC
使用CEF
創建我們的CWebView
#pragma once
#include <cef_client.h>
class CWebClient
: public CefClient
, public CefLifeSpanHandler
{
protected:
CefRefPtr<CefBrowser> m_Browser;
public:
CWebClient(void){};
virtual ~CWebClient(void){};
CefRefPtr<CefBrowser> GetBrowser() { return m_Browser; }
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE
{ return this; }
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE;
// 添加CEF的SP虛函數
IMPLEMENT_REFCOUNTING(CWebClient);
IMPLEMENT_LOCKING(CWebClient);
};
接下來就開始修改我們的視圖類了:
// CWebView message handlers
int CWebView::OnCreate( LPCREATESTRUCT lpCreateStruct )
{
if ( CView::OnCreate(lpCreateStruct) == -1)
return -1;
CefRefPtr<CWebClient> client(new CWebClient());
m_cWebClient = client;
CefSettings cSettings;
CefSettingsTraits::init( &cSettings);
cSettings.multi_threaded_message_loop = true;
CefRefPtr<CefApp> spApp;
CefInitialize( cSettings, spApp);
CefWindowInfo info;
info.SetAsChild( m_hWnd, CRect(0, 0, 800, 600));
CefBrowserSettings browserSettings;
CefBrowser::CreateBrowser( info, static_cast<CefRefPtr<CefClient> >(client),
"http://192.168.1.21:8080/dialysis/web/page/nav/content.jsp", browserSettings);
return 0;
}
調整大小:
void CWebView::OnSize( UINT nType, int cx, int cy )
{
CView::OnSize(nType, cx, cy);
if(m_cWebClient.get())
{
CefRefPtr<CefBrowser> browser = m_cWebClient->GetBrowser();
if(browser)
{
CefWindowHandle hwnd = browser->GetWindowHandle();
RECT rect;
this->GetClientRect(&rect);
// ::SetWindowPos(hwnd, HWND_TOP, 0, 0, cx, cy, SWP_NOZORDER);
::MoveWindow( hwnd, 0, 0, cx, cy, true);
}
}
}
如果在編譯CWebView出現連接錯誤可以把libcef_dll_wrapper工程的Runtime Library修改爲Multi-threaded Debug DLL (/MDd) 並將Treat warnings as errors修改爲No (/WX-)試試。