65.9K
CodeProject 正在变化。 阅读更多。
Home

在MFC C++应用程序中使用WebView2 Edge浏览器

starIconstarIconstarIconstarIconstarIcon

5.00/5 (24投票s)

2020年12月3日

CPOL

3分钟阅读

viewsIcon

118252

downloadIcon

8157

C++,WebView2,Edge浏览器,在MFC应用程序中使用Edge

引言

长期以来,在桌面应用程序环境中,微软一直使用Internet Explorer作为网页浏览器控件。但现在情况正在发生变化。微软希望我们停止使用Internet Explorer并切换到Edge。

在这个例子中,我们将看到如何在基于对话框的应用程序中添加webView2(Edge浏览器)作为网页浏览器控件。这非常简单。

背景

技术发展日新月异,浏览器也是如此。与Chrome和Mozilla等现代浏览器相比,Internet Explorer已经落后了。为了弥补这一点,微软现在切换到了基于Chromium的Edge。

Using the Code

首先,使用Visual Studio创建一个默认的基于对话框的MFC应用程序。构建应用程序,构建完成后,我们将开始在项目中添加webview2

请遵循以下步骤

  1. 首先,在您的PC上安装webview2运行时。网址如下 --> <https://developer.microsoft.com/en-us/microsoft-edge/webview2/>
  2. 然后添加Nuget包,转到Visual Studio --> 项目 --> 管理Nuget包

    在这里,您需要搜索并安装两个包(WebView2Microsoft.Windows.ImplementationLibrary)。

    重要提示:请升级到webview2的1.0.622.22版本。以下代码在WebView2包的预发行版本上无效。

  3. 添加包后,再次构建您的程序。完成后,在“stdafx.h”头文件中添加以下头文件。
    #include <wrl.h>
    #include "WebView2EnvironmentOptions.h"
    #include "WebView2.h"
  4. 打开对话框实现文件,并在OnInitDialog()方法中初始化此内容
    HRESULT hresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    InitializeWebView();
  5. 现在,我们在下面的方法中初始化webview2。这三个方法是相互依赖的。如果第一个方法成功,断点将进入第二个方法。如果第二个方法成功,断点将进入第三个方法。

    在第三个函数中,您需要提供要导航到的URL。

    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;
    }

更多详情,您可以下载附加的示例并在您的应用程序中尝试。

现在,我更新了项目解决方案,并删除了WebView2Loader.dll依赖项。您可以直接运行.exe,因为我已经将此库静态链接到项目中。

如果它对您有用,请给这篇文章评5星!谢谢!

必备组件

WebView2支持以下编程环境

  • Win32 C/C++ (GA)
  • .NET Framework 4.6.2或更高版本
  • .NET Core 3.1或更高版本
  • .NET 5
  • WinUI 3.0 (预览版)

确保您已在支持的操作系统(目前为Windows 10、Windows 8.1和Windows 7)上安装了Microsoft Edge(Chromium)和WebView2 SDK。

根据我的经验,WebView2在Windows 7和8上的表现不佳。所以我个人建议将WebView2用于Windows 10及更高版本。

您必须安装具有C++支持的Visual Studio 2015或更高版本

 

最近的增强

从现在开始,我们可以无需WIL引用即可编译此项目。我已经将其从项目中移除并进行了必要的更改。

关注点

网上关于webview2的内容不多,因为它现在还比较新。但我认为在这里创建这篇文章来帮助其他人很重要。

历史

  • 2020年12月3日:初始版本
  • 2021年3月1日:更新了解决方案
© . All rights reserved.