Click here to Skip to main content
15,891,184 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.5K   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: 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 
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 
AnswerRe: I have updates Pin
Ayush Swiss16-Jun-22 21:20
Ayush Swiss16-Jun-22 21:20 
GeneralRe: I have updates Pin
Scot Brennecke17-Jun-22 3:41
professionalScot Brennecke17-Jun-22 3:41 
Yes, the source here on CP had the changes to use WRL instead of wil. I applied those changes to the source I cloned from your repo on GitHub.
As for the .NET stuff, I think you are referring to this article
Introduction to Microsoft Edge WebView2 - Microsoft Edge Development | Microsoft Docs[^]
WebView2 is available for those programming environments (including .NET 6, too). But .NET is not required at all.

Another important change I made to your sources is that I fixed the bug you had for some configurations naming the wrong PCH header, and other configurations not using it at all. With my fixes, they all properly use stdafx.h.
(I also resolved some level 4 warning for the cleanest compile).
Scot Brennecke
Software Developer
VC++ Specialist

GeneralRe: I have updates Pin
Ayush Swiss17-Jun-22 3:49
Ayush Swiss17-Jun-22 3:49 
GeneralRe: I have updates Pin
Scot Brennecke17-Jun-22 4:05
professionalScot Brennecke17-Jun-22 4:05 
QuestionWIL problems Pin
Charalambos Ioannides13-Jun-22 1:34
Charalambos Ioannides13-Jun-22 1:34 
AnswerRe: WIL problems Pin
Ayush Swiss13-Jun-22 22:46
Ayush Swiss13-Jun-22 22:46 
AnswerRe: WIL problems Pin
Ayush Swiss13-Jun-22 22:53
Ayush Swiss13-Jun-22 22:53 
GeneralRe: WIL problems Pin
Charalambos Ioannides13-Jun-22 23:24
Charalambos Ioannides13-Jun-22 23:24 
GeneralRe: WIL problems Pin
Ayush Swiss14-Jun-22 2:20
Ayush Swiss14-Jun-22 2:20 
GeneralRe: WIL problems Pin
Charalambos Ioannides14-Jun-22 12:30
Charalambos Ioannides14-Jun-22 12:30 
GeneralRe: WIL problems Pin
Ayush Swiss14-Jun-22 23:47
Ayush Swiss14-Jun-22 23:47 
GeneralRe: WIL problems Pin
Charalambos Ioannides15-Jun-22 1:17
Charalambos Ioannides15-Jun-22 1:17 
GeneralRe: WIL problems Pin
Ayush Swiss15-Jun-22 2:10
Ayush Swiss15-Jun-22 2:10 
GeneralRe: WIL problems Pin
Ayush Swiss15-Jun-22 4:58
Ayush Swiss15-Jun-22 4:58 
QuestionHow can i wait until response is complete Pin
tom11116-May-22 2:28
tom11116-May-22 2:28 
AnswerRe: How can i wait until response is complete Pin
Ayush Swiss16-May-22 4:15
Ayush Swiss16-May-22 4:15 
GeneralRe: How can i wait until response is complete Pin
tom11118-May-22 22:31
tom11118-May-22 22:31 
GeneralRe: How can i wait until response is complete Pin
Ayush Swiss19-May-22 0:21
Ayush Swiss19-May-22 0:21 
GeneralRe: How can i wait until response is complete Pin
tom11119-May-22 1:41
tom11119-May-22 1:41 

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.