Click here to Skip to main content
15,884,473 members
Articles / Desktop Programming / Win32
Tip/Trick

WebView2 Edge Browser in MFC C++ Application

Rate me:
Please Sign up or sign in to vote.
5.00/5 (26 votes)
15 Jun 2022CPOL3 min read 96.3K   7.7K   47   91
C++, WebView2, Edge Browser, Edge in MFC application
This is a sample application that is very easy to understand and user friendly. I hope it will help you in your WebView adventure.

Image 1

Introduction

For a long time in the desktop application environment, from the Microsoft side, we have Internet Explorer support as the web browser control. But now things are changing with Internet Explorer. Now, Microsoft also wants us to stop using Internet Explorer and switch to Edge.

In this example, we will see how to add webView2 (Edge browser) as the web browser control in our dialog based application. It's very easy.

Background

Technology is changing very fast, so are browsers. Internet Explorer is lagging behind in comparison with other modern browsers like Chrome and Mozilla. To cover this up, Microsoft has now switched to Chromium-based Edge.

Using the Code

First, make a default Dialog based MFC application by using Visual Studio. Build the application once the build is complete, then we will start adding webview2 in the project.

Follow these steps:

  1. First, install the webview2 runtime on your PC. URL is given here --> <https://developer.microsoft.com/en-us/microsoft-edge/webview2/>
  2. Then add the Nuget packages, go to Visual Studio --> Projects --> Manage Nuget Packages

    Here, you need to search and install two packages (WebView2 and Microsoft.Windows.ImplementationLibrary).

    Important: Please upgrade to 1.0.622.22 version of webview2. The below code will not work on the pre-release version of the WebView2 package.

    Image 2

  3. After adding the packages, build your program again. Once done, add the below headers in "stdafx.h" header file.
    C++
    #include <wrl.h>
    #include "WebView2EnvironmentOptions.h"
    #include "WebView2.h"
  4. Open the dialog implementation file and in OnInitDialog() method, initialize this:
    C++
    HRESULT hresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    InitializeWebView();
  5. Now we initialize the webview2 in the below method. These three methods are interdependent. If the first one succeeds, the breakpoint will go in the second one. If the second one succeeds, the breakpoint will go in the third one.

    And in the third function, you need to provide the URL which you want to navigate.

    C++
    void CEdgeBrowserAppDlg::InitializeWebView()
    {
        CloseWebView();
        m_dcompDevice = nullptr;
    
        HRESULT hr2 = DCompositionCreateDevice2(nullptr, IID_PPV_ARGS(&m_dcompDevice));
        if (!SUCCEEDED(hr2))
        {
            AfxMessageBox(L"Attempting to create WebView 
                          using DComp Visual is not supported.\r\n"
                "DComp device creation failed.\r\n"
                "Current OS may not support DComp.\r\n"
                "Create with Windowless DComp Visual Failed", MB_OK);
            return;
        }
    
    #ifdef USE_WEBVIEW2_WIN10
        m_wincompCompositor = nullptr;
    #endif
        LPCWSTR subFolder = nullptr;
        auto options = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>();
        options->put_AllowSingleSignOnUsingOSPrimaryAccount(FALSE);
    
    
        HRESULT hr = CreateCoreWebView2EnvironmentWithOptions
                     (subFolder, nullptr, options.Get(), 
                     Microsoft::WRL::Callback
                     <ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>
                     (this, &CEdgeBrowserAppDlg::OnCreateEnvironmentCompleted).Get());
    
    
        if (!SUCCEEDED(hr))
        {
            if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
            {
                TRACE("Couldn't find Edge installation. 
                Do you have a version installed that is compatible with this ");
            }
            else
            {
                AfxMessageBox(L"Failed to create webview environment");
            }
        }
    }
    
    HRESULT CEdgeBrowserAppDlg::OnCreateEnvironmentCompleted
            (HRESULT result, ICoreWebView2Environment* environment)
    {
        m_webViewEnvironment = environment;
        m_webViewEnvironment->CreateCoreWebView2Controller
        (this->GetSafeHwnd(), Microsoft::WRL::Callback
        <ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>
        (this, &CEdgeBrowserAppDlg::OnCreateCoreWebView2ControllerCompleted).Get());
    
        return S_OK;
    }
    
    HRESULT CEdgeBrowserAppDlg::OnCreateCoreWebView2ControllerCompleted
                                (HRESULT result, ICoreWebView2Controller* controller)
    {
        if (result == S_OK)
        {
            m_controller = controller;
            Microsoft::WRL::ComPtr<ICoreWebView2> coreWebView2;
            m_controller->get_CoreWebView2(&coreWebView2);
            m_webView = coreWebView2.Get();
    
            NewComponent<ViewComponent>(
                this, m_dcompDevice.Get(),
    #ifdef USE_WEBVIEW2_WIN10
                m_wincompCompositor,
    #endif
                m_creationModeId == IDM_CREATION_MODE_TARGET_DCOMP);
    
               HRESULT hresult = m_webView->Navigate
                                 (L"https://ayushshyam.wixsite.com/perdesijaat");
    
            if (hresult == S_OK)
            {
                TRACE("Web Page Opened Successfully");
                ResizeEverything();
            }
        }
        else
        {
            TRACE("Failed to create webview");
        }
        return S_OK;
    }

For more details, you can download the sample attached and try it in your application.

Now, I updated the project solution, and WebView2Loader.dll dependency is removed. You can just run the .exe because I statically linked this library in the project.

If it's working for you or helps you by any means, then please rate this post 5 stars! Thank you!

Prerequisites

WebView2 supports the following programming environments:

  • Win32 C/C++ (GA)
  • .NET Framework 4.6.2 or later
  • .NET Core 3.1 or later
  • .NET 5
  • WinUI 3.0 (Preview)

Make sure you have installed both Microsoft Edge (Chromium) and the WebView2 SDK installed on the supported OS (currently Windows 10, Windows 8.1, and Windows 7).

From my experience, WebView2 is not behaving well on Windows 7 and 8. So I personally can recommend the WebView2 for Windows 10 and above.

You must have Visual Studio 2015 or later with C++ support installed.

 

Recent Enhancement:

From now, we can compile this project without WIL reference. I removed it from the project and made the required changes. 

Points of Interest

There is not so much content over the web about webview2 because it's new at this moment. But I thought it was important to create this post here to help others.

History

  • 3rd December, 2020: Initial version
  • 1st March, 2021: Updated the solution

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Switzerland Switzerland
Hello,

I am Ayush Chaudhary from the beautiful country of India. I have over 13 years of experience with application design and development. For 5 years, I have been living in Switzerland and working here as a Technical Consultant in a nice Swiss Company.

In my career, I have been working with many technologies, but trust me I am not sure which one is my favorite. I am confused between C#, Java, C++, MS SQL, IBM Informix, Android development, and many more.


Comments and Discussions

 
QuestionHow can it be extended to inlcude newer methods such as WebResourceResponseReceived? Pin
Robert Ibsen Voith27-Nov-23 5:02
Robert Ibsen Voith27-Nov-23 5:02 
AnswerRe: How can it be extended to inlcude newer methods such as WebResourceResponseReceived? Pin
Ayush Swiss29-Nov-23 0:14
Ayush Swiss29-Nov-23 0:14 
GeneralRe: How can it be extended to inlcude newer methods such as WebResourceResponseReceived? Pin
Robert Ibsen Voith29-Nov-23 7:36
Robert Ibsen Voith29-Nov-23 7:36 
QuestionWhy there is a new folder named 'EdgeBrowserApp.exe.WebView2' in the same folder? Pin
mbncvbut23-Apr-23 3:49
mbncvbut23-Apr-23 3:49 
AnswerRe: Why there is a new folder named 'EdgeBrowserApp.exe.WebView2' in the same folder? Pin
mbncvbut25-Apr-23 0:43
mbncvbut25-Apr-23 0:43 
GeneralRe: Why there is a new folder named 'EdgeBrowserApp.exe.WebView2' in the same folder? Pin
Ayush Swiss25-Apr-23 1:05
Ayush Swiss25-Apr-23 1:05 
QuestionCan we put WebView2Loader.dll in subfolder like /libs and load it from there Pin
anh72-Apr-23 19:05
anh72-Apr-23 19:05 
AnswerRe: Can we put WebView2Loader.dll in subfolder like /libs and load it from there Pin
Ayush Swiss25-Apr-23 1:08
Ayush Swiss25-Apr-23 1:08 
GeneralMy vote of 5 Pin
germanredcat11-Jan-23 11:20
germanredcat11-Jan-23 11:20 
GeneralRe: My vote of 5 Pin
Ayush Swiss11-Jan-23 22:11
Ayush Swiss11-Jan-23 22:11 
QuestionAny idea how to get notification of NavigateComplete Pin
bits&bytes2-Jan-23 8:57
bits&bytes2-Jan-23 8:57 
AnswerRe: Any idea how to get notification of NavigateComplete Pin
Ayush Swiss11-Jan-23 22:14
Ayush Swiss11-Jan-23 22:14 
GeneralRe: Any idea how to get notification of NavigateComplete Pin
bits&bytes12-Jan-23 8:05
bits&bytes12-Jan-23 8:05 
QuestionHow did you remove WebView2Loader.dll dependency? Pin
scpark981-Dec-22 20:21
scpark981-Dec-22 20:21 
AnswerRe: How did you remove WebView2Loader.dll dependency? Pin
duderduder114-Feb-23 10:15
duderduder114-Feb-23 10:15 
QuestionRun in a child window of a Dialog Pin
Warren Whitfield20-Oct-22 21:11
Warren Whitfield20-Oct-22 21:11 
QuestionCompiles but... Pin
pggcoding23-Aug-22 16:57
pggcoding23-Aug-22 16:57 
AnswerRe: Compiles but... Pin
Ayush Swiss10-Oct-22 3:40
Ayush Swiss10-Oct-22 3:40 
QuestionThis is a really great program. Pin
klrodel25-Jul-22 23:37
klrodel25-Jul-22 23:37 
AnswerRe: This is a really great program. Pin
Ayush Swiss25-Jul-22 23:50
Ayush Swiss25-Jul-22 23:50 
GeneralRe: This is a really great program. Pin
klrodel26-Jul-22 14:34
klrodel26-Jul-22 14:34 
QuestionProblems running Pin
Michael Haephrati17-Jun-22 4:10
professionalMichael Haephrati17-Jun-22 4:10 
I get an error saying it can't run on my machine (Windows 10)
- Michael Haephrati מיכאל האפרתי

AnswerRe: Problems running Pin
Ayush Swiss17-Jun-22 4:24
Ayush Swiss17-Jun-22 4:24 
AnswerRe: Problems running Pin
Michael Haephrati17-Jun-22 5:11
professionalMichael Haephrati17-Jun-22 5:11 
QuestionI have updates Pin
Scot Brennecke16-Jun-22 9:26
professionalScot Brennecke16-Jun-22 9:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.