C++ 在Win32中简单使用WebView2

webView2简介

Microsoft Edge WebView2 控件允许在本机应用中嵌入 web 技术(HTML、CSS 以及 JavaScript)。 WebView2 控件使用 Microsoft Edge 作为绘制引擎,以在本机应用中显示 web 内容。
使用 WebView2 可以在本机应用的不同部分嵌入 Web 代码,或在单个 WebView2 实例中生成所有本机应用。可以去官网查看具体信息,比如支持哪些系统,这是比较重要的(抄袭官网的 ps: 手动狗头)
ps: webVIew2 简介

环境准备:
1.visual studio 2022 (虽然有点新,但是和其他版本差不多)
2.WebView2 是需要 Microsoft Edge WebView2 Runtime支持

检查自己是否安装了 Microsoft Edge WebView2 Runtime
在这里插入图片描述

相信大家怎么找到这个位置(继续狗头)。

如果没有下载的话:
下载链接:webView2 双击即可下载

搭建环境

最好以管理员方式运行 visual studio

1.创建一个Win32项目
在这里插入图片描述ps: visual studio 2022

创建完成
在这里插入图片描述
2.添加WebView2依赖
选中项目,点击鼠标右键,并找到“ 管理 NuGet 程序包… ” 选项
在这里插入图片描述
在这里插入图片描述
注意看右上角红色框,没有使用过NuGet的大概率是没有这个,所以现在先添加程序包源
在这里插入图片描述
点击设置按钮会出现一个对话框。如下图在这里插入图片描述
没有使用过NuGet的同学应该只有第二个程序包没有第一个,首先在弹出的对话框中找到NuGet包管理器,选中程序包源,在右上角有个加号添加程序包源添加完成之后,还需要点击一下更新,最后再点击确认。
包名: nuget.org
包源 https://api.nuget.org/v3/index.json

添加好程序包源之后,在搜索框里直接搜索webView2,选中并直接点击安装,在之后的对话框中选择Ok,等待安装完成。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
还需要安装一个依赖是ImplementationLibrary,安装过程和webView2一样。
在这里插入图片描述
至此需要的程序包源已经下载完成,开始添加依赖项。(如果不能搜索出结果,可能需要科学上网,咳咳)

3.添加依赖项
找到生成依赖项
在这里插入图片描述
选中 依赖项->生成自定义 会弹出一个对话框。点击查找现有按钮
在这里插入图片描述
找到你项目存放的位置,下面会生成一个Packages文件夹
在这里插入图片描述
找到WebView2.target文件,路径已经用红色框标出来,选中文件,点击打开。
在这里插入图片描述
第二个依赖
在这里插入图片描述
选中添加的两个依赖,点击确定。
在这里插入图片描述
至此,WebView2的环境搭建完成。

4.测试
先贴上 测试代码 复制粘贴即可
在这里插入图片描述

#include "framework.h"
#include "Demo.h" ///记得修改
#include <windows.h>
#include <strsafe.h>
#include <io.h>
#include <stdlib.h>
#include <string>
#include <tchar.h>
#include <wrl.h>
#include <wil/com.h>
#include <AccCtrl.h>
#include <AclAPI.h>

#include "webView2.h"
using namespace Microsoft::WRL;

// Global variables

// The main window class name.
static TCHAR szWindowClass[] = _T("DesktopApp");

// The string that appears in the application's title bar.
static TCHAR szTitle[] = _T("WebView");

HINSTANCE hInst;

// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

// Pointer to WebViewController
static wil::com_ptr<ICoreWebView2Controller> webviewController;

// Pointer to WebView window
static wil::com_ptr<ICoreWebView2> webviewWindow;

int CALLBACK WinMain(
    _In_ HINSTANCE hInstance,
    _In_ HINSTANCE hPrevInstance,
    _In_ LPSTR     lpCmdLine,
    _In_ int       nCmdShow
)
{
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = szWindowClass;
    wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);

    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Windows Desktop Guided Tour"),
            NULL);

        return 1;
    }
    // Store instance handle in our global variable
    hInst = hInstance;

    // The parameters to CreateWindow explained:
    // szWindowClass: the name of the application
    // szTitle: the text that appears in the title bar
    // WS_OVERLAPPEDWINDOW: the type of window to create
    // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
    // 500, 100: initial size (width, length)
    // NULL: the parent of this window
    // NULL: this application does not have a menu bar
    // hInstance: the first parameter from WinMain
    // NULL: not used in this application
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        680, 600,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Windows Desktop Guided Tour"),
            NULL);

        return 1;
    }

    // The parameters to ShowWindow explained:
    // hWnd: the value returned from CreateWindow
    // nCmdShow: the fourth parameter from WinMain
    ShowWindow(hWnd,
        nCmdShow);
    UpdateWindow(hWnd);

    // <-- WebView2 sample code starts here -->

    HRESULT res = CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
        Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
            [hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
                //MessageBoxA(hWnd, "createView", "", NULL);
                // Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd
                env->CreateCoreWebView2Controller(hWnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
                    [hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
                        if (controller != nullptr) {
                            webviewController = controller;
                            webviewController->get_CoreWebView2(&webviewWindow);
                        }

                        // Add a few settings for the webview
                        // The demo step is redundant since the values are the default settings
                        ICoreWebView2Settings* Settings;
                        webviewWindow->get_Settings(&Settings);
                        Settings->put_IsScriptEnabled(TRUE);
                        Settings->put_AreDefaultScriptDialogsEnabled(TRUE);
                        Settings->put_IsWebMessageEnabled(TRUE);

                        // Resize WebView to fit the bounds of the parent window
                        RECT bounds;
                        GetClientRect(hWnd, &bounds);
                        webviewController->put_Bounds(bounds);

                        // Schedule an async task to navigate to Bing

                        HRESULT res = webviewWindow->Navigate(L"https:\\www.baidu.com");
                        std::string sres = std::to_string(res).c_str();
                        // Step 4 - Navigation events

                        // Step 5 - Scripting

                        // Step 6 - Communication between host and web content

                        return S_OK;
                    }).Get());
                return S_OK;
            }).Get());
    // <-- WebView2 sample code ends here -->

    // Main message loop:
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int)msg.wParam;
}

//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_DESTROY  - post a quit message and return
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_SIZE:
        if (webviewController != nullptr) {
            RECT bounds;
            GetClientRect(hWnd, &bounds);
            webviewController->put_Bounds(bounds);
        };
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }
    return 0;
}

5.运行结果
在这里插入图片描述

好了,c++ win32 WebView2的环境搭建以及简单使用就完成了,如果有写的不好的地方,请各位多多谅解啦。各位不要忘了点赞呀,如果有什么问题可以发邮箱交流哟。1719427391@qq.com

  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值