方案一:使用Microsoft WebView2(推荐Windows平台)1. 环境准备[size=16.002px]
[size=16.002px]
2. 创建C++ Win32项目
[C++] 纯文本查看 复制代码 // main.cpp
#include <Windows.h>
#include <wrl.h>
#include <WebView2.h>
using namespace Microsoft::WRL;
ComPtr<ICoreWebView2Controller> webviewController;
ComPtr<ICoreWebView2> webview;
// 窗口消息处理函数
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// 初始化WebView2
void InitializeWebView(HWND hWnd) {
CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
[hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
env->CreateCoreWebView2Controller(hWnd,
Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
[](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
if (controller != nullptr) {
webviewController = controller;
webviewController->get_CoreWebView2(&webview);
}
// 加载HTML内容
webview->NavigateToString(
L"<html><body><h1>Hello from C++!</h1></body></html>");
return S_OK;
}).Get());
return S_OK;
}).Get());
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) {
// 创建窗口
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = L"WebViewWindow";
RegisterClass(&wc);
HWND hWnd = CreateWindowEx(0, L"WebViewWindow", L"HTML in C++ Window",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
nullptr, nullptr, hInstance, nullptr);
InitializeWebView(hWnd);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// 消息循环
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
方案二:使用Qt WebEngine(跨平台)
1. 安装Qt[size=16.002px]
2. 项目配置(.pro文件)
QT += core gui webenginewidgets TARGET = HtmlInCpp SOURCES += main.cpp
3. 代码实现
[C++] 纯文本查看 复制代码 // main.cpp
#include <QApplication>
#include <QWebEngineView>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWebEngineView view;
view.setHtml("<h1>Hello from Qt!</h1>");
view.show();
return app.exec();
}
|