Skip to content

快速上手

环境要求

依赖版本
Visual Studio2019 / 2022(MSVC,C++17)
CMake≥ 3.15
Windows SDK10
WebView2 RuntimeWin10/11 通常自带;缺则装 Evergreen Runtime
Python 3可选,启用 .7z 压缩时构建期需要(py7zr)

WIL / nlohmann_json / doctest 已 vendored 进 third_party/,clone 即得,零联网。WebView2 SDK 由 cmake/webview2_sdk.cmake 解析(本地副本优先 → 否则 NuGet 配置期下载)。

构建框架本身

bash
cd webview
cmake -B build -G "Visual Studio 17 2022" -A x64
cmake --build build --config Debug

产物:

产物说明
build/Debug/webview.lib导入库 h::webview(static)
build/Debug/webview.exeGUI demo,逐按钮验全部功能
build/Debug/webview_tests.exe纯逻辑单测(doctest)

跑单测:

bash
build/Debug/webview_tests.exe

作为导入库消费

cmkr 项目消费 h::webviewcmake.toml

toml
[fetch-content]
webview = { dir = "E:/leanrnCode/c++ project/webview" }

[target.myapp]
type = "executable"
sources = ["src/main.cpp"]
link-libraries = ["h::webview"]

伞头:

cpp
#include "webview/webview.hpp"   // app / window / bridge / menu / tray / value
using namespace webview;

Hello World

最小可运行窗口 + 一条 RPC:

cpp
#include "webview/app.hpp"
#include "webview/window.hpp"
using namespace webview;

int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
    auto& app = App::instance();
    if (!app.requestSingleInstanceLock()) return 1;   // 单实例

    Window::Opts opts;
    opts.title  = L"my app";
    opts.width  = 1000;
    opts.height = 700;
    opts.center = true;
    auto win = app.createWindow(std::move(opts));

    // JS → C++:注册一个槽
    win->on("add", [](int a, int b) { return a + b; });

    // 加载本地打包资源(约定目录)
    win->loadURL(L"src/assets/html/index.html");

    return app.run();
}

前端 JS 端 runtime.js 自动注入,提供 window.bridge

js
// 调 C++ 的 add 槽
const sum = await bridge.call('add', 2, 3);   // → 5

// 反向:JS 注册、C++ 调
bridge.on('greet', name => 'hello ' + name);

C++ 反向调 JS:

cpp
std::string reply = win->call<std::string>("greet", "world");   // → "hello world"

资源约定目录

把前端 dist 放进消费方的约定目录:

myapp/
  src/
    main.cpp
    assets/html/        ← 约定目录,库 fetch 时自动打包
      index.html
      assets/...

opts.url = L"src/assets/html/index.html" 命中约定目录,下次 cmake --build 自动把整目录嵌入 exe。详见 HTML 资源打包

下一步