Click here to Skip to main content
15,890,557 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 97.4K   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

 
AnswerRe: Failing to build the solution with VS 2015 Pin
Ayush Swiss14-Feb-22 23:30
Ayush Swiss14-Feb-22 23:30 
GeneralRe: Failing to build the solution with VS 2015 Pin
Member 359211615-Feb-22 12:18
Member 359211615-Feb-22 12:18 
GeneralRe: Failing to build the solution with VS 2015 Pin
Ayush Swiss22-Feb-22 23:36
Ayush Swiss22-Feb-22 23:36 
QuestionAccess to an URL with datas in method POST doesn't work Pin
Member 99469559-Feb-22 2:20
Member 99469559-Feb-22 2:20 
QuestionWebView2 Document Pin
Juergen Broschinski30-Jan-22 19:56
Juergen Broschinski30-Jan-22 19:56 
AnswerRe: WebView2 Document Pin
Ayush Swiss22-Feb-22 23:52
Ayush Swiss22-Feb-22 23:52 
QuestionCan't follow instructions or download the source code Pin
Andrew Truckle29-Jun-21 6:06
professionalAndrew Truckle29-Jun-21 6:06 
QuestionWhat about things like Print Preview? And what about in a CDialogEx project? Pin
Andrew Truckle29-Jun-21 2:15
professionalAndrew Truckle29-Jun-21 2:15 
Thanks.

AnswerRe: What about things like Print Preview? And what about in a CDialogEx project? Pin
Andrew Truckle29-Jun-21 6:07
professionalAndrew Truckle29-Jun-21 6:07 
QuestionAccess to microphone in WebView2 Pin
TSchind10-Jun-21 5:43
TSchind10-Jun-21 5:43 
AnswerRe: Access to microphone in WebView2 Pin
TSchind11-Jun-21 5:56
TSchind11-Jun-21 5:56 
GeneralMy vote of 5 Pin
Member 38872521-Jun-21 20:25
Member 38872521-Jun-21 20:25 
QuestionGreat Project. Need to prevent new window popups. Pin
dilipvpv31-May-21 23:30
dilipvpv31-May-21 23:30 
AnswerRe: Great Project. Need to prevent new window popups. Pin
Ayush Swiss31-May-21 23:39
Ayush Swiss31-May-21 23:39 
GeneralRe: Great Project. Need to prevent new window popups. Pin
dilipvpv1-Jun-21 5:18
dilipvpv1-Jun-21 5:18 
QuestionIs it blood on your forehead? Pin
yongunlee12-May-21 18:33
yongunlee12-May-21 18:33 
AnswerRe: Is it blood on your forehead? Pin
Ayush Swiss17-May-21 1:15
Ayush Swiss17-May-21 1:15 
GeneralRe: Is it blood on your forehead? Pin
yongunlee1-Jun-21 22:17
yongunlee1-Jun-21 22:17 
QuestionUnable to start program Pin
dipakkumar29-Apr-21 7:21
dipakkumar29-Apr-21 7:21 
AnswerRe: Unable to start program Pin
tiresias224-Jul-21 1:33
tiresias224-Jul-21 1:33 
QuestionI got an error: Pin
Southmountain5-Feb-21 12:47
Southmountain5-Feb-21 12:47 
AnswerRe: I got an error: Pin
Ayush Swiss8-Feb-21 0:03
Ayush Swiss8-Feb-21 0:03 
Suggestiontips to build this project Pin
Southmountain5-Feb-21 12:44
Southmountain5-Feb-21 12:44 
QuestionPlease make it clear what dependencies exist Pin
Mike Diack2-Feb-21 0:10
Mike Diack2-Feb-21 0:10 
AnswerRe: Please make it clear what dependencies exist Pin
Ayush Swiss2-Feb-21 0:34
Ayush Swiss2-Feb-21 0:34 

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.