Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

WebView2 Edge Browser in MFC C++ Application

5.00/5 (26 votes)
15 Jun 2022CPOL3 min read 114K   8K  
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)