MCPcopy Create free account
hub / github.com/MicrosoftEdge/WebView2Samples / CloseWebView

Method CloseWebView

SampleApps/WebView2APISample/AppWindow.cpp:2610–2720  ·  view source on GitHub ↗

[Close] Close the WebView and deinitialize related state. This doesn't close the app window.

Source from the content-addressed store, hash-verified

2608//! [Close]
2609// Close the WebView and deinitialize related state. This doesn't close the app window.
2610bool AppWindow::CloseWebView(bool cleanupUserDataFolder)
2611{
2612 if (auto file = GetComponent<FileComponent>())
2613 {
2614 if (file->IsPrintToPdfInProgress())
2615 {
2616 int selection = MessageBox(
2617 m_mainWindow, L"Print to PDF is in progress. Continue closing?",
2618 L"Print to PDF", MB_YESNO);
2619 if (selection == IDNO)
2620 {
2621 return false;
2622 }
2623 }
2624 }
2625 // 1. Delete components.
2626 DeleteAllComponents();
2627
2628 // 2. If cleanup needed and BrowserProcessExited event interface available,
2629 // register to cleanup upon browser exit.
2630 wil::com_ptr<ICoreWebView2Environment5> environment5;
2631 if (m_webViewEnvironment)
2632 {
2633 environment5 = m_webViewEnvironment.try_query<ICoreWebView2Environment5>();
2634 }
2635 if (cleanupUserDataFolder && environment5)
2636 {
2637 // Before closing the WebView, register a handler with code to run once the
2638 // browser process and associated processes are terminated.
2639 CHECK_FAILURE(environment5->add_BrowserProcessExited(
2640 Callback<ICoreWebView2BrowserProcessExitedEventHandler>(
2641 [environment5, this](
2642 ICoreWebView2Environment* sender,
2643 ICoreWebView2BrowserProcessExitedEventArgs* args)
2644 {
2645 COREWEBVIEW2_BROWSER_PROCESS_EXIT_KIND kind;
2646 UINT32 pid;
2647 CHECK_FAILURE(args->get_BrowserProcessExitKind(&kind));
2648 CHECK_FAILURE(args->get_BrowserProcessId(&pid));
2649
2650 // If a new WebView is created from this CoreWebView2Environment after
2651 // the browser has exited but before our handler gets to run, a new
2652 // browser process will be created and lock the user data folder
2653 // again. Do not attempt to cleanup the user data folder in these
2654 // cases. We check the PID of the exited browser process against the
2655 // PID of the browser process to which our last CoreWebView2 attached.
2656 if (pid == m_newestBrowserPid)
2657 {
2658 // Watch for graceful browser process exit. Let ProcessFailed event
2659 // handler take care of failed browser process termination.
2660 if (kind == COREWEBVIEW2_BROWSER_PROCESS_EXIT_KIND_NORMAL)
2661 {
2662 CHECK_FAILURE(environment5->remove_BrowserProcessExited(
2663 m_browserExitedEventToken));
2664 // Release the environment only after the handler is invoked.
2665 // Otherwise, there will be no environment to raise the event when
2666 // the collection of WebView2 Runtime processes exit.
2667 m_webViewEnvironment = nullptr;

Callers

nothing calls this directly

Calls 1

Tested by

no test coverage detected