在MFC中嵌入Chromium Embedded Framework


官方MFC+CEF例子:https://bitbucket.org/TSS_DEV/cef-mfc/src/default/
學習參考:https://www.codeproject.com/Articles/1105945/Embedding-a-Chromium-Browser-in-an-MFC-Application
CEF3的二進制發行版可從https://cefbuilds.com/獲得,其中包括以下內容:

  • CEF共享庫(libcef)及其依賴項的調試和發布版本
  • 使用CEF的C ++應用程序所必需的C ++包裝靜態庫(libcef_dll_wrapper)
  • 兩個示例應用程序(cefsimple和cefclient)
  • 使用CEF的應用程序資源
  • CEF的調試和發布符號(作為單獨下載)

出於本文的目的,我們將使用CEF的二進制分發。
因此,本文的前提條件是:

  • 來自開發分支機構(樹干)的最新CEF 64位版本(cef_binary_79.0.10+ge866a07+chromium-79.0.3945.88_windows64)
  • Visual Studio 2017(因為CEF已與此版本一起編譯)

一個MFC SDI應用程序主要包含CWinApp、CFrameWnd、CDocument以及CView等組件。
另一方面,基於CEF的應用程序具有以下組件:

  • 初始化CEF並運行CEF消息循環的入口點。
  • 一個CefApp派生類,用於處理特定於進程的回調。
  • CefClient派生的類,用於處理特定於瀏覽器實例的回調(可以包括瀏覽器生命周期,上下文菜單,對話框,顯示通知,拖動事件,焦點事件,鍵盤事件等的回調)。 CefClient的單個實例可以在任意數量的瀏覽器之間共享。
  • 使用CefBrowserHost::CreateBrowser()創建的一個或多個CefBrowser實例。

要將Chromium瀏覽器嵌入到MFC應用程序中,我們需要:

  • 啟動應用程序時初始化CEF;這應該在CWinApp::InitInstance()重寫方法中完成
  • 應用程序存在時取消初始化CEF; 這應該在CWinApp::ExitInstance()重寫方法中完成
  • 實現CefClient來處理特定於瀏覽器實例的回調;CefClient的實例存儲在CView派生類中。 創建視圖時,我們還必須創建一個CefBrowser作為視圖的子視圖,並將其顯示在視圖頂部,並始終保持其大小與視圖相同。

PS: libcef_dll_wrapper.lib使用MDd(Debug)和MD(Release)方式構建
創建cefmfcdemo工程,注意以下設置:

  • 從32位創建一個64位項目目標復制設置。
  • 確保$(SolutionDir)$(Configuration)\是所有平台和配置的輸出(這意味着CEF主文件夾中的Debug和Release文件夾)。
  • 更改VC ++目錄,並將.\添加到包含目錄,並將$(SolutionDir)\lib\$(Configuration)\添加到Library目錄。
  • 將libcef.lib和libcef_dll_wrapper.lib添加到鏈接器的其他依賴項。
  • 在運行應用程序之前,將Resources文件夾的內容復制到Debug and Release,因為它包含CEF框架所需的資源。
ClientHandler.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
 
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#ifndef  CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_
#define  CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_

#include   "include/base/cef_lock.h"
#include   "include/cef_client.h"

class  ClientHandler :  public  CefClient,
    
public  CefDisplayHandler,
    
public  CefLifeSpanHandler,
    
public  CefLoadHandler
{
public :
    
// Implement this interface to receive notification of ClientHandler
     // events. The methods of this class will be called on the main thread.
     class  Delegate
    {
    
public :
        
// Called when the browser is created.
         virtual   void  OnBrowserCreated(CefRefPtr<CefBrowser> browser) =  0 ;

        
// Called when the browser is closing.
         virtual   void  OnBrowserClosing(CefRefPtr<CefBrowser> browser) =  0 ;

        
// Called when the browser has been closed.
         virtual   void  OnBrowserClosed(CefRefPtr<CefBrowser> browser) =  0 ;

        
// Set the window URL address.
         virtual   void  OnSetAddress(std::string  const  &url) =  0 ;

        
// Set the window title.
         virtual   void  OnSetTitle(std::string  const  &title) =  0 ;

        
// Set fullscreen mode.
         virtual   void  OnSetFullscreen( bool   const  fullscreen) =  0 ;

        
// Set the loading state.
         virtual   void  OnSetLoadingState( bool   const  isLoading,
                                       
bool   const  canGoBack,
                                       
bool   const  canGoForward) =  0 ;

    
protected :
        
virtual  ~Delegate() {}
    };

public :
    ClientHandler(Delegate *delegate);
    ~ClientHandler();

    
void  CreateBrowser(CefWindowInfo  const  &info, CefBrowserSettings  const  &settings, CefString  const  &url);

    
// CefClient methods:
     virtual  CefRefPtr<CefDisplayHandler> GetDisplayHandler() override
    {
        
return   this ;
    }
    
virtual  CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override
    {
        
return   this ;
    }
    
virtual  CefRefPtr<CefLoadHandler> GetLoadHandler() override
    {
        
return   this ;
    }

    
// CefDisplayHandler methods:
     virtual   void  OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,  const  CefString &url) override;
    
virtual   void  OnTitleChange(CefRefPtr<CefBrowser> browser,  const  CefString &title) override;
    
virtual   void  OnFullscreenModeChange(CefRefPtr<CefBrowser> browser,  bool  fullscreen) override;

    
// CefLifeSpanHandler methods:
     virtual   void  OnAfterCreated(CefRefPtr<CefBrowser> browser) override;
    
virtual   bool  DoClose(CefRefPtr<CefBrowser> browser) override;
    
virtual   void  OnBeforeClose(CefRefPtr<CefBrowser> browser) override;

    
// CefLoadHandler methods:
     virtual   void  OnLoadingStateChange(CefRefPtr<CefBrowser> browser,
                                      
bool  isLoading,
                                      
bool  canGoBack,
                                      
bool  canGoForward) override;

    
virtual   void  OnLoadError(CefRefPtr<CefBrowser> browser,
                             CefRefPtr<CefFrame> frame,
                             ErrorCode errorCode,
                             
const  CefString &errorText,
                             
const  CefString &failedUrl) override;

    
// This object may outlive the Delegate object so it's necessary for the
     // Delegate to detach itself before destruction.
     void  DetachDelegate();

private :

    
// Include the default reference counting implementation.
    IMPLEMENT_REFCOUNTING(ClientHandler);
    
// Include the default locking implementation.
    IMPLEMENT_LOCKING(ClientHandler);

private :
    Delegate *m_delegate;
};

#endif    // CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_
 ClientHandler.cpp 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
 
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include   "stdafx.h"
#include   "ClientHandler.h"

#include  <sstream>
#include  <string>

#include   "include/base/cef_bind.h"
#include   "include/cef_app.h"
#include   "include/wrapper/cef_closure_task.h"
#include   "include/wrapper/cef_helpers.h"

ClientHandler::ClientHandler(Delegate *delegate)
    : m_delegate(delegate)
{
}

ClientHandler::~ClientHandler()
{
}

void  ClientHandler::CreateBrowser(CefWindowInfo  const  &info, CefBrowserSettings  const  &settings, CefString  const  &url)
{
    CefBrowserHost::CreateBrowser(info, 
this , url, settings, nullptr, nullptr);
}

void  ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,  const  CefString &url)
{
    CEF_REQUIRE_UI_THREAD();

    
// Only update the address for the main (top-level) frame.
     if (frame->IsMain())
    {
        
if (m_delegate != nullptr)
            m_delegate->OnSetAddress(url);
    }
}

void  ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser,  const  CefString &title)
{
    CEF_REQUIRE_UI_THREAD();

    
if (m_delegate != nullptr)
        m_delegate->OnSetTitle(title);
}

void  ClientHandler::OnFullscreenModeChange(CefRefPtr<CefBrowser> browser,  bool  fullscreen)
{
    CEF_REQUIRE_UI_THREAD();

    
if (m_delegate != nullptr)
        m_delegate->OnSetFullscreen(fullscreen);
}

void  ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser)
{
    CEF_REQUIRE_UI_THREAD();

    
if (m_delegate != nullptr)
        m_delegate->OnBrowserCreated(browser);
}

bool  ClientHandler::DoClose(CefRefPtr<CefBrowser> browser)
{
    CEF_REQUIRE_UI_THREAD();

    
if (m_delegate != nullptr)
        m_delegate->OnBrowserClosing(browser);

    
return   false ;
}

void  ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser)
{
    CEF_REQUIRE_UI_THREAD();

    
if (m_delegate != nullptr)
        m_delegate->OnBrowserClosed(browser);
}

void  ClientHandler::OnLoadError(CefRefPtr<CefBrowser> browser,
                                CefRefPtr<CefFrame> frame,
                                ErrorCode errorCode,
                                
const  CefString &errorText,
                                
const  CefString &failedUrl)
{
    CEF_REQUIRE_UI_THREAD();

    
// Don't display an error for downloaded files.
     if (errorCode == ERR_ABORTED)
        
return ;

    
// Display a load error message.
    std::stringstream ss;
    ss << 
"<html><body bgcolor=\" white\ ">"
       
"<h2>Failed to load URL "  << std::string(failedUrl) <<
       
" with error "  << std::string(errorText) <<  " ("  << errorCode <<
       
").</h2></body></html>" ;
    
//frame->LoadString(ss.str(), failedUrl);
    frame->LoadURL(CefString(ss.str()));
}

void  ClientHandler::OnLoadingStateChange(CefRefPtr<CefBrowser> browser,  bool  isLoading,  bool  canGoBack,  bool  canGoForward)
{
    CEF_REQUIRE_UI_THREAD();

    
if (m_delegate != nullptr)
        m_delegate->OnSetLoadingState(isLoading, canGoBack, canGoForward);
}

void  ClientHandler::DetachDelegate()
{
    m_delegate = nullptr;
}
 CefView.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
 

// CefView.h : interface of the CefView class
//

#pragma  once

#include   "ClientHandler.h"

class  CefView :  public  CView,  public  ClientHandler::Delegate
{
protected // create from serialization only
    CefView();
    DECLARE_DYNCREATE(CefView)

    
// Attributes
public :
    CefDoc *GetDocument() 
const ;

    
// Operations
public :
    
void  Navigate(CString  const  &url);
    
void  NavigateBack();
    
void  NavigateForward();
    
bool  CanNavigateBack();
    
bool  CanNavigateForward();
    
void  CloseBrowser();

    
// Overrides
public :
    
virtual   void  OnDraw(CDC *pDC);   // overridden to draw this view
     virtual  BOOL PreCreateWindow(CREATESTRUCT &cs);
    
virtual   void  OnActivateView(BOOL bActivate, CView *pActivateView, CView *pDeactiveView);
    
virtual  BOOL PreTranslateMessage(MSG *pMsg);
protected :

    
// Implementation
public :
    
virtual  ~CefView();
#ifdef  _DEBUG
    
virtual   void  AssertValid()  const ;
    
virtual   void  Dump(CDumpContext &dc)  const ;
#endif

protected :
    
virtual   void  OnBrowserCreated(CefRefPtr<CefBrowser> browser) override;

    
// Called when the browser is closing.
     virtual   void  OnBrowserClosing(CefRefPtr<CefBrowser> browser) override;

    
// Called when the browser has been closed.
     virtual   void  OnBrowserClosed(CefRefPtr<CefBrowser> browser) override;

    
// Set the window URL address.
     virtual   void  OnSetAddress(std::string  const  &url) override;

    
// Set the window title.
     virtual   void  OnSetTitle(std::string  const  &title) override;

    
// Set fullscreen mode.
     virtual   void  OnSetFullscreen( bool   const  fullscreen) override;

    
// Set the loading state.
     virtual   void  OnSetLoadingState( bool   const  isLoading,
                                   
bool   const  canGoBack,
                                   
bool   const  canGoForward) override;

    
// Generated message map functions
protected :
    DECLARE_MESSAGE_MAP()

    
virtual   void  OnInitialUpdate();
    
void  OnSize(UINT nType,  int  cx,  int  cy);

private :
    
void  InitStartUrl();

    CefRefPtr<ClientHandler> m_clientHandler;
    CefRefPtr<CefBrowser> m_browser;
    CWnd *m_wndMain = nullptr;
    CString m_startUrl;
};

#ifndef  _DEBUG   // debug version in CefView.cpp
inline  CefDoc *CefView::GetDocument()  const
{
    
return   reinterpret_cast <CefDoc *>(m_pDocument);
}
#endif

 CefView.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
 

// CefView.cpp : implementation of the CefView class
//

#include   "stdafx.h"
// SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail
// and search filter handlers and allows sharing of document code with that project.
#ifndef  SHARED_HANDLERS
#include   "cefmfcdemo.h"
#endif

#include   "CefDoc.h"
#include   "CefView.h"
#include   "CefWindowsHelpers.h"
#include   "include\internal\cef_string_wrappers.h"
#include   "MainFrm.h"

#ifdef  _DEBUG
#define   new  DEBUG_NEW
#endif


// CefView

IMPLEMENT_DYNCREATE(CefView, CView)

BEGIN_MESSAGE_MAP(CefView, CView)
    ON_WM_SIZE()
END_MESSAGE_MAP()

// CefView construction/destruction

CefView::CefView()
{
    
// TODO: add construction code here

}

CefView::~CefView()
{
    
if (m_clientHandler != nullptr)
        m_clientHandler->DetachDelegate();
}

BOOL CefView::PreCreateWindow(CREATESTRUCT &cs)
{
    
// TODO: Modify the Window class or styles here by modifying
     //  the CREATESTRUCT cs

    
return  CView::PreCreateWindow(cs);
}

void  CefView::OnActivateView(BOOL bActivate, CView *pActivateView, CView *pDeactiveView)
{
    m_wndMain = AfxGetMainWnd();

    
return  CView::OnActivateView(bActivate, pActivateView, pDeactiveView);
}

// CefView drawing

void  CefView::OnDraw(CDC *  /*pDC*/ )
{
    CefDoc *pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    
if  (!pDoc)
        
return ;

    
// TODO: add draw code for native data here
}


// CefView diagnostics

#ifdef  _DEBUG
void  CefView::AssertValid()  const
{
    CView::AssertValid();
}

void  CefView::Dump(CDumpContext &dc)  const
{
    CView::Dump(dc);
}

CefDoc *CefView::GetDocument() 
const   // non-debug version is inline
{
    ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CefDoc)));
    
return  (CefDoc *)m_pDocument;
}
#endif   //_DEBUG


void  CefView::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
{
    m_browser = browser;
}

void  CefView::OnBrowserClosing(CefRefPtr<CefBrowser> browser)
{
}

void  CefView::OnBrowserClosed(CefRefPtr<CefBrowser> browser)
{
    
if (m_browser != nullptr &&
            m_browser->GetIdentifier() == browser->GetIdentifier())
    {
        m_browser = nullptr;

        m_clientHandler->DetachDelegate();
    }
}

void  CefView::OnSetAddress(std::string  const  &url)
{
    
auto  main =  static_cast <CMainFrame *>(m_wndMain);
    
if (main != nullptr)
    {
        
auto  newurl = CString {url.c_str()};
        
if (newurl.Find(m_startUrl) >=  0 )
            newurl = 
"" ;

        main->SetUrl(newurl);
    }
}

void  CefView::OnSetTitle(std::string  const  &title)
{
    ::SetWindowText(m_hWnd, CefString(title).ToWString().c_str());
}

void  CefView::OnSetFullscreen( bool   const  fullscreen)
{
    
if (m_browser != nullptr)
    {
        
if (fullscreen)
        {
            CefWindowsHelpers::Maximize(m_browser);
        }
        
else
        {
            CefWindowsHelpers::Restore(m_browser);
        }
    }
}

void  CefView::OnSetLoadingState( bool   const  isLoading,
                                
bool   const  canGoBack,
                                
bool   const  canGoForward)
{
}

void  CefView::OnInitialUpdate()
{
    CView::OnInitialUpdate();

    InitStartUrl();

    
auto  rect = RECT{ 0 };
    GetClientRect(&rect);

    CefWindowInfo info;
    info.SetAsChild(GetSafeHwnd(), rect);

    CefBrowserSettings browserSettings;
    browserSettings.web_security = STATE_DISABLED;

    m_clientHandler = 
new  ClientHandler( this );
    m_clientHandler->CreateBrowser(info, browserSettings, CefString(m_startUrl));
}

void  CefView::OnSize(UINT nType,  int  cx,  int  cy)
{
    CView::OnSize(nType, cx, cy);

    
if (m_clientHandler != nullptr)
    {
        
if (m_browser != nullptr)
        {
            
auto  hwnd = m_browser->GetHost()->GetWindowHandle();
            
auto  rect = RECT { 0 };
            GetClientRect(&rect);

            ::SetWindowPos(hwnd, HWND_TOP, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER);
        }
    }
}

BOOL CefView::PreTranslateMessage(MSG *pMsg)
{
    
if (pMsg->message == WM_KEYDOWN)
    {
        
if (pMsg->wParam == VK_F5)
        {
            m_browser->Reload();
        }
    }

    
return  CView::PreTranslateMessage(pMsg);
}

void  CefView::Navigate(CString  const  &url)
{
    
if (m_browser != nullptr)
    {
        
auto  frame = m_browser->GetMainFrame();
        
if (frame != nullptr)
        {
            frame->LoadURL(CefString(url));
        }
    }
}

void  CefView::NavigateBack()
{
    
if (m_browser != nullptr)
    {
        m_browser->GoBack();
    }
}

void  CefView::NavigateForward()
{
    
if (m_browser != nullptr)
    {
        m_browser->GoForward();
    }
}

bool  CefView::CanNavigateBack()
{
    
return  m_browser != nullptr && m_browser->CanGoBack();
}

bool  CefView::CanNavigateForward()
{
    
return  m_browser != nullptr && m_browser->CanGoForward();
}

void  CefView::InitStartUrl()
{
    TCHAR path_buffer[_MAX_PATH] = {
0 };
    TCHAR drive[_MAX_DRIVE] = {
0 };
    TCHAR dir[_MAX_DIR] = {
0 };
    TCHAR fname[_MAX_FNAME] = {
0 };
    TCHAR ext[_MAX_EXT] = {
0 };

    ::GetModuleFileName(
NULL , path_buffer,  sizeof (path_buffer));
    
auto  err = _tsplitpath_s(path_buffer, drive, _MAX_DRIVE, dir, _MAX_DIR, fname, _MAX_FNAME, ext, _MAX_EXT);
    
if (err !=  0 ) {}

    
auto  s = CString{dir};
    s += _T(
"html" );
    err = _tmakepath_s(path_buffer, _MAX_PATH, drive, (LPCTSTR)s, _T(
"index" ), _T( "html" ));
    
if (err !=  0 ) {}

    m_startUrl = CString {path_buffer};
    m_startUrl.Replace(_T(
'\\' ), _T( '/' ));
    m_startUrl = CString {_T(
"file:///" )} + m_startUrl;
}

void  CefView::CloseBrowser()
{
    
if (m_browser != nullptr)
    {
        ::DestroyWindow(m_browser->GetHost()->GetWindowHandle());
        
//m_browser->GetHost()->CloseBrowser(true);
    }
}
CefMfcdDemoApp.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 

// cefmfcdemo.h : main header file for the cefmfcdemo application
//
#pragma  once

#ifndef  __AFXWIN_H__
#error   "include 'stdafx.h' before including this file for PCH"
#endif

#include   "resource.h"         // main symbols

#include   "include/cef_base.h"
#include   "include/cef_app.h"

// CefMfcdDemoApp:
// See cefmfcdemo.cpp for the implementation of this class
//

class  CefMfcdDemoApp :  public  CWinApp
{
public :
    CefMfcdDemoApp();


    
// Overrides
public :
    
virtual  BOOL InitInstance();
    
virtual   int  ExitInstance();
    
virtual  BOOL PumpMessage() override;

    
// Implementation
    afx_msg  void  OnAppAbout();
    DECLARE_MESSAGE_MAP()

private :
    
void  InitializeCef();
    
void  UninitializeCef();
    
bool  m_bCEFInitialized;
    CefRefPtr<CefApp> m_app;
};

extern  CefMfcdDemoApp theApp;
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
 

// cefmfcdemo.cpp : Defines the class behaviors for the application.
//

#include   "stdafx.h"
#include   "afxwinappex.h"
#include   "afxdialogex.h"
#include   "cefmfcdemo.h"
#include   "MainFrm.h"

#include   "CefDoc.h"
#include   "CefView.h"

#ifdef  _DEBUG
#define   new  DEBUG_NEW
#endif


// CefMfcdDemoApp

BEGIN_MESSAGE_MAP(CefMfcdDemoApp, CWinApp)
    ON_COMMAND(ID_APP_ABOUT, &CefMfcdDemoApp::OnAppAbout)
    
// Standard file based document commands
    ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew)
    ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen)
END_MESSAGE_MAP()


// CefMfcdDemoApp construction

CefMfcdDemoApp::CefMfcdDemoApp()
{
    
// support Restart Manager
    m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS;
#ifdef  _MANAGED
    
// If the application is built using Common Language Runtime support (/clr):
     //     1) This additional setting is needed for Restart Manager support to work properly.
     //     2) In your project, you must add a reference to System.Windows.Forms in order to build.
    System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException);
#endif

    
// TODO: replace application ID string below with unique ID string; recommended
     // format for string is CompanyName.ProductName.SubProduct.VersionInformation
    SetAppID(_T( "cefmfcdemo.AppID.NoVersion" ));

    
// TODO: add construction code here,
     // Place all significant initialization in InitInstance
    m_bCEFInitialized =  false ;
}

// The one and only CefMfcdDemoApp object

CefMfcdDemoApp theApp;


// CefMfcdDemoApp initialization

BOOL CefMfcdDemoApp::InitInstance()
{
    
// InitCommonControlsEx() is required on Windows XP if an application
     // manifest specifies use of ComCtl32.dll version 6 or later to enable
     // visual styles.  Otherwise, any window creation will fail.
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = 
sizeof (InitCtrls);
    
// Set this to include all the common control classes you want to use
     // in your application.
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    InitializeCef();

    CWinApp::InitInstance();


    
// Initialize OLE libraries
     if  (!AfxOleInit())
    {
        AfxMessageBox(IDP_OLE_INIT_FAILED);
        
return  FALSE;
    }

    AfxEnableControlContainer();

    EnableTaskbarInteraction(FALSE);

    
// AfxInitRichEdit2() is required to use RichEdit control
     // AfxInitRichEdit2();

    
// Standard initialization
     // If you are not using these features and wish to reduce the size
     // of your final executable, you should remove from the following
     // the specific initialization routines you do not need
     // Change the registry key under which our settings are stored
     // TODO: You should modify this string to be something appropriate
     // such as the name of your company or organization
    SetRegistryKey(_T( "Local AppWizard-Generated Applications" ));
    LoadStdProfileSettings(
0 );   // Load standard INI file options (including MRU)


    
// Register the application's document templates.  Document templates
     //  serve as the connection between documents, frame windows and views
    CSingleDocTemplate *pDocTemplate;
    pDocTemplate = 
new  CSingleDocTemplate(
        IDR_MAINFRAME,
        RUNTIME_CLASS(CefDoc),
        RUNTIME_CLASS(CMainFrame),       
// main SDI frame window
        RUNTIME_CLASS(CefView));
    
if  (!pDocTemplate)
        
return  FALSE;
    AddDocTemplate(pDocTemplate);


    
// Parse command line for standard shell commands, DDE, file open
    CCommandLineInfo cmdInfo;
    ParseCommandLine(cmdInfo);



    
// Dispatch commands specified on the command line.  Will return FALSE if
     // app was launched with /RegServer, /Register, /Unregserver or /Unregister.
     if  (!ProcessShellCommand(cmdInfo))
        
return  FALSE;

    
// The one and only window has been initialized, so show and update it
    m_pMainWnd->ShowWindow(SW_SHOW);
    m_pMainWnd->UpdateWindow();
    
return  TRUE;
}

int  CefMfcdDemoApp::ExitInstance()
{
    
//TODO: handle additional resources you may have added
    AfxOleTerm(FALSE);

    UninitializeCef();

    
return  CWinApp::ExitInstance();
}

BOOL CefMfcdDemoApp::PumpMessage()
{
    
if  (m_bCEFInitialized)
        CefDoMessageLoopWork();

    
return  CWinApp::PumpMessage();
}

// CefMfcdDemoApp message handlers


// CAboutDlg dialog used for App About

class  CAboutDlg :  public  CDialogEx
{
public :
    CAboutDlg();

    
// Dialog Data
     enum  { IDD = IDD_ABOUTBOX };

protected :
    
virtual   void  DoDataExchange(CDataExchange *pDX);     // DDX/DDV support

    
// Implementation
protected :
    DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void  CAboutDlg::DoDataExchange(CDataExchange *pDX)
{
    CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()

// App command to run the dialog
void  CefMfcdDemoApp::OnAppAbout()
{
    CAboutDlg aboutDlg;
    aboutDlg.DoModal();
}

// CefMfcdDemoApp message handlers


void  CefMfcdDemoApp::InitializeCef()
{
    CefMainArgs mainargs(m_hInstance);

    CefSettings settings;
    settings.multi_threaded_message_loop = 
false ;

    m_bCEFInitialized = CefInitialize(mainargs, settings, m_app, nullptr);
}

void  CefMfcdDemoApp::UninitializeCef()
{
    CefShutdown();
}

運行截圖:

參考完整代碼下載:
百度雲盤: https://pan.baidu.com/s/1LS7991sp29xooX67X8wxog 提取碼: 2wvi 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM