C++ 在Win32中简单使用WebView2

这篇具有很好参考价值的文章主要介绍了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
C++ 在Win32中简单使用WebView2

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

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

搭建环境

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

1.创建一个Win32项目
C++ 在Win32中简单使用WebView2ps: visual studio 2022

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

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

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

4.测试
先贴上 测试代码 复制粘贴即可
C++ 在Win32中简单使用WebView2

#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

好了,c++ win32 WebView2的环境搭建以及简单使用就完成了,如果有写的不好的地方,请各位多多谅解啦。各位不要忘了点赞呀,如果有什么问题可以发邮箱交流哟。1719427391@qq.com文章来源地址https://www.toymoban.com/news/detail-458336.html

到了这里,关于C++ 在Win32中简单使用WebView2的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C# Winform 中使用 Webview2

    目前的windows/Linux下的UI方案,以Qt为主,Flutter, Electron为辅,其他的各种UI都是不堪大用。众所周知,Electron的资源占用和内容占用太大,效率不行,所以有了后续各种跨语言的Web套壳方案: walls go语言下web套壳 tarui Rust下的web套壳 除了使用CEF的Qt/C++/C#方案,Qt+WebEngine, 目前在

    2024年02月12日
    浏览(36)
  • 四.Winform使用Webview2加载本地HTML页面并互相通信

    往期相关文章目录 专栏目录 实现刷新按钮 点击 C# winform 按钮可以调用 C# winform 代码显示到html上 点击 HTML 按钮可以调用 C# winform 代码更改html按钮字体 C# - html html-C# 确保mainView2的CoreWebView2异步初始化完成 在webview2的CoreWebView初始化之后设置属性 在coreWebview2完成时添加 WebMess

    2024年01月24日
    浏览(35)
  • c#使用webView2 访问本地静态html资源跨域Cors问题

    在浏览器中访问本地静态资源html网页时,可能会遇到跨域问题如图。   是因为浏览器默认启用了同源策略,即只允许加载与当前网页具有相同源(协议、域名和端口)的内容。 WebView2默认情况下启用了浏览器的同源策略,即只允许加载与主机相同源的内容。所以如果我们把

    2024年02月20日
    浏览(33)
  • c#使用webView2 访问本地静态html资源跨域Cors问题 (附带代理服务helper帮助类)

    在浏览器中访问本地静态资源html网页时,可能会遇到跨域问题如图。   是因为浏览器默认启用了同源策略,即只允许加载与当前网页具有相同源(协议、域名和端口)的内容。 WebView2默认情况下启用了浏览器的同源策略,即只允许加载与主机相同源的内容。所以如果我们把

    2024年02月21日
    浏览(32)
  • 一.Winform使用Webview2(Edge浏览器核心) 创建demo(Demo1)实现回车导航到指定地址

    往期相关文章目录 专栏目录 WinForms 应用中的 WebView2 入门 按照官方文档一路操作,可以自行百度或者查看WinForms 应用中的 WebView2 入门。为了避坑,本人安装的时vs2022(visual studio 以下简称vs) 打开vs(visual studio 以下简称vs) 点击 创建新项目 ,选择 C# Windows 窗体应用 (.NET Framework

    2024年02月21日
    浏览(34)
  • WebView2 的初步集成与试用

    目录 一、环境概况 二、安装 三、集成测试  参考资料         由于以前公司自己集成了一个浏览器供客户使用,而原来的浏览器使用的是IWebBrowser2的技术,而IWebBrowser2技术支持的IE框架只能到ie11,但由于现在新的js框架横行,而且加上windows放弃了IE浏览器,而有的客户项目

    2024年02月05日
    浏览(35)
  • winform嵌入浏览器 webView2

    1、项目引用nuget 2、winform窗体中初始化 3、webView2中的js调用c#代码

    2024年02月10日
    浏览(32)
  • QT5 通过 webview2 加载网页

    官方文档参考:https://learn.microsoft.com/zh-cn/microsoft-edge/webview2/get-started/win32 头文件主要为:WebView2和WixLibrary,存储在include/external 库主要为:WebView2LoaderStatic.lib和WebView2Loader.dll,存储在lib/external CMakeLists文件 base/set_env.cmake init_project.cmake base/set_compile_arg.cmake main函数 MainWindow函数

    2024年02月07日
    浏览(36)
  • NET Webview2无法打开网页解决方法

    错误情况: 用.NET 开发 使用Webview2 打开网页时,白屏,不显示网页。 系统错误日志: Code Integrity determined that a process (DeviceHarddiskVolume7Program Files (x86)MicrosoftEdgeWebViewApplication110.0.1587.63msedgewebview2.exe) attempted to load DeviceHarddiskVolume7InetPubftprootTiprayLdTermghijt64.dll that did

    2024年02月15日
    浏览(38)
  • Java Swing 嵌入微软 WebView2 的运行环境设置

    当使用 DJNativeSwing 和 Eclipse swt 开发 Windows 桌面 Java 应用时,因为使用 Javascript 动态载入 html 片段, 导致 CORS 异常. Access to XMLHttpRequest at ‘file:///…’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, ch

    2024年02月10日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包