WebView2启动本地前端项目

// compile with: /D_UNICODE /DUNICODE /DWIN32 /D_WINDOWS /c

#include <windows.h>
#include <stdlib.h>
#include <string>
#include <tchar.h>
#include <wrl.h>
#include <wil/com.h>
// <IncludeHeader>
// include WebView2 header
#include "WebView2.h"
#include "WebView2EnvironmentOptions.h"
// </IncludeHeader>
#include "resource.h"

#define MAX_DIR_LEN 1024

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[MAX_DIR_LEN] = _T("WebView sample");

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

static boolean isOpenCurDir = true;

int CALLBACK wWinMain(
	_In_ HINSTANCE hInstance,
	_In_ HINSTANCE hPrevInstance,
	_In_ LPWSTR lpCmdLine,
	_In_ int nCmdShow)
{
	if (wcslen(lpCmdLine) == 0)
	{
		GetCurrentDirectoryW(MAX_DIR_LEN, szTitle);
	}
	else
	{
		wcscpy(szTitle, lpCmdLine);
		isOpenCurDir = false;
	}

	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, MAKEINTRESOURCE(IDI_ICON1));
	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,
		CW_USEDEFAULT, CW_USEDEFAULT,
		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 -->
	// Step 3 - Create a single WebView within the parent window
	// Locate the browser and set up the environment for WebView
	auto options = Make<CoreWebView2EnvironmentOptions>();
	options->put_AdditionalBrowserArguments(L"--disable-web-security");

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

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

																									 webview->add_NewWindowRequested(Callback<ICoreWebView2NewWindowRequestedEventHandler>(
																																		 [hWnd](ICoreWebView2 *sender, ICoreWebView2NewWindowRequestedEventArgs *args)
																																		 {
																																			 args->put_Handled(TRUE);
																																			 LPWSTR uri = nullptr;
																																			 args->get_Uri(&uri);
																																			 webview->Navigate(uri);
																																			 CoTaskMemFree(uri);
																																			 return S_OK;
																																		 })
																																		 .Get(),
																																	 nullptr);

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

																									 if (isOpenCurDir)
																									 {
																										 auto host = std::to_wstring((long long)hInstance) + L".webview2";
																										 auto url = L"https://" + host + L"/index.html";
																										 webview.try_query<ICoreWebView2_3>()->SetVirtualHostNameToFolderMapping(host.c_str(), L".", COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_ALLOW);
																										 webview->Navigate(url.c_str());
																									 }
																									 else
																									 {
																										 webview->Navigate(szTitle);
																									 }
																									 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)
{
	TCHAR greeting[] = _T("Hello, Windows desktop!");

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值