CWebView::Attach Method  
 
BOOL Attach(
  HWND hWndHost,  
  LPCTSTR lpszUrl  
);
BOOL Attach(
  HWND hWndHost,  
  DWORD dwOptions,  
  LPCTSTR lpszUrl,  
  LPCTSTR lpszLanguage,  
  LPCTSTR lpszDataFolder  
);

The Attach method attaches a new instance of the browser control to a host window.

Parameters

hWndHost
A handle to the window that will serve as a container for the browser control. This may either be a top-level application window or a child window. If the handle does not specify a valid window, the method will fail. This parameter is required and cannot be NULL.
dwOptions
One or more option bitflags. For more information, refer to the Options documentation. Most applications should not use a value of zero for this parameter. If no options are specified, the browser instance will be created with a very restrictive set of permissions that can prevent many websites from functioning correctly.
lpszUrl
A null-terminated string which specifies the initial URL the browser should navigate to after the control has been attached to the window. If this parameter is NULL or an empty string, the browser instance will be created with a blank page. The only schemes permitted are https://, http:// and file://. If a domain name is specified without a scheme, it will default to using https://.
lpszLanguage
A null-terminated string which specifies an alternate language to use when the browser displays a context menu or dialogs. This value can be a standard language tag in BCP-47 format (such as "en-US") or it can be a string which specifies a hexadecimal Windows locale identifier (such as "0x0409"). It is recommended you use the language tag whenever possible, as Microsoft is deprecating the use of locale identifiers (LCIDs) and their associated APIs. If this parameter is a NULL pointer or an empty string, the browser will use the current default language for the local user.
lpszDataFolder
A folder name where the user profile data will be stored. This is the location where the browser will cache viewed pages, store cookies and form data, and where scripts may store session data. This value may be just a name (such as the name of the application) or an absolute path. If the folder name contains environment variables surrounded in percent (%) symbols, they will be replaced with their value in the current user's environment. If folder name does specify an absolute path, the profile will be stored in the current user's LocalAppData folder. If this parameter is NULL or an empty string, a temporary profile will be created for the session and then automatically deleted when the session ends.

Return Value

If the method succeeds, the return value is non-zero. If the method fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The Attach method binds a new WebView instance to an existing top-level or child window you have already created. The host window must be created on the current UI thread and remain valid for the lifetime of the WebView. Do not call this method from a worker thread or for a window that was created by another thread; if a background thread needs a browser, create a dedicated window on that thread or use Create instead. Only one WebView instance can be attached to a given host window at a time. If you need to recreate the browser, call Detach before attaching again.

The calling thread must be in a single-threaded apartment (STA). During initialization the library calls CoInitializeEx as needed and if your process has already initialized COM as MTA (COINIT_MULTITHREADED), the attach will fail. This requirement comes directly from the Edge WebView2 control which cannot be created in an MTA COM application.

The dwOptions parameter enables you to specify what features are enabled in the browser. It is recommended that most applications use WEBVIEW_OPTION_ENABLE_DEFAULT which enables functionality which is most commonly found in web browsers. If you want your host application to exchange messages with scripts executing in the browser, you should also specify the WEBVIEW_OPTION_ENABLE_MESSAGES options. This option must be enabled to use PostWebMessage and GetWebMessage methods.

When clicking on a link would normally open that page in a new tab or browser window, it will be redirected to the primary browser window by default. This ensures that the browser control retains focus and all events are within the context of that window. If you wish to permit the creation of popup windows and/or support the creation of new browser windows (for example, if a link target is "_blank") then specify the WEBVIEW_OPTION_ENABLE_NEW_WINDOWS option. Note that if you permit the creation of new popup windows, it can shift focus away from your main browser window. There is no mechanism in the API to enumerate the child popup windows and they are independent of the window attached to the browser.

By default, the browser will use the language associated with the current user's locale. If you specify an alternate language, this also affects what languages the browser includes with the Accept-Language request header. This will provide hints to the website as to what language is preferred when it returns content to the browser. However, it does not guarantee that a website will return content in that language and will not automatically cause a page to be translated from one language to another.

If you pass NULL or an empty string for the lpszDataFolder parameter, the library creates a temporary, per-session user-data folder under the current user's LocalAppData folder. That folder is flagged as temporary and is automatically deleted when you detach the WebView from the window via Detach. If you pass a relative path (such as "MyApp"), the library creates or uses that folder beneath %LocalAppData%\WebView, creating a folder path like %LocalAppData%\WebView\MyApp.

If you pass a fully qualified path as the lpszDataFolder parameter, it will use that path. However, it will not accept paths to unsafe locations and will return an error if your application does not have permission to create a folder in that location. If there are environment variables surrounded by percent (%) symbols, those variables will be expanded when the folder path is resolved. If you enable privacy mode with WEBVIEW_OPTION_ENABLE_PRIVACY, the library will ensure the profile is unique to the session by appending a GUID to the base folder and treating it as temporary. The GetUserDataFolder method can be used to obtain the full path to the data folder being used.

When multiple WebView instances point at the same user-data folder, they share a single WebView2 profile created with that folder path. In this configuration the browser cache, cookies, history, and site storage are persisted under that folder and are reused across windows and processes, which speeds up subsequent navigations and preserves sign-in/session state. The library passes your folder directly to WebView2 when creating the environment, so any instance using that same path participates in the same profile, and you can clear portions of that profile at runtime via the provided helpers for cache, history, and cookies.

Your WEBVIEWEVENTPROC event callback function is invoked on the same thread that owns the WebView window. Because events are raised on the UI thread, long-running work in an event handler can block the user interface and stall navigation. Where possible, defer heavy operations to background threads. You should avoid displaying modal dialogs or message boxes from within event handlers. Also note that some events may fire multiple times during a single navigation. For example, the security state can transition through several levels (unknown, neutral, secure, or warning) before settling on a final value. Applications should be written to handle these changes incrementally.

To present correctly inside a resizable child window, resize the browser view when the host window size changes. The library tracks the host window position but relies on your WM_SIZE handling to drive layout.

Example

#include "cstools12.h"

// Windows message handler
static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

// WebView event handler for navigation and security events
static VOID CALLBACK WebViewEvents(HWND hWnd, UINT uEvent, WPARAM wParam, LPARAM lParam, DWORD_PTR dwParam)
{
    switch (uEvent)
    {
    case WEBVIEW_EVENT_NAVIGATION_STARTING:
        OutputDebugString(_T("[WebView] Navigation starting\n"));
        break;

    case WEBVIEW_EVENT_NAVIGATION_COMPLETED:
        if (wParam)
            OutputDebugString(_T("[WebView] Navigation completed\n"));
        else
            OutputDebugString(_T("[WebView] Navigation failed\n"));
        break;

    case WEBVIEW_EVENT_SECURITY_CHANGED:
        OutputDebugString(_T("[WebView] Security changed\n"));
        break;
    }
}

INT WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, INT nCmdShow)
{
    if (!WebViewInitialize(CSTOOLS12_LICENSE_KEY, NULL))
    {
        MessageBox(NULL, _T("Unable to initialize the WebView API"), _T("Error"), MB_ICONEXCLAMATION);
        return 0;
    }

    LPCTSTR kClass = _T("MyWebViewWndClass");
    WNDCLASS wc{};
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszClassName = kClass;
    RegisterClass(&wc);

    HWND hWnd = Create(0, kClass, _T("WebView"),
                               WS_OVERLAPPEDWINDOW,
                               CW_USEDEFAULT, CW_USEDEFAULT, 1024, 720,
                               NULL, NULL, hInstance, NULL);

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // A standard Windows message loop
    MSG uMsg;

    while (GetWebMessage(&uMsg, nullptr, 0, 0))
    {
        TranslateMessage(&uMsg);
        DispatchMessage(&uMsg);
    }

    WebViewUninitialize();
    return (int)uMsg.wParam;
}

static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_CREATE:
        // Create a WebView2 browser instance and attach to this window
        {
            DWORD dwOptions = WEBVIEW_OPTION_ENABLE_DEFAULT;
            LPCTSTR pszInitialUrl = _T("https://example.com");
            LPCTSTR pszDataFolder = _T("MyTestApp");

            if (!WebViewAttach(hWnd, dwOptions, pszInitialUrl, NULL, pszDataFolder, WebViewEvents, 0))
            {
                 MessageBox(NULL, _T("Unable to attach the WebView2 control"), _T("Error"), MB_ICONEXCLAMATION);
            }
        }
        return 0;

    case WM_SIZE:
        // Make sure the browser window resizes with the window
        {
            RECT rc;
            GetClientRect(hWnd, &rc);
            WebViewSetBounds(hWnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top);
        }
        return 0;

    case WM_DESTROY:
        // Detach the WebView2 browser instance from the window
        WebViewDetachWindow(hWnd);
        PostQuitMessage(0);
        return 0;
    }

    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

Requirements

Minimum Desktop Platform: Windows 7 Service Pack 1
Minimum Server Platform: Windows Server 2008 R2 Service Pack 1
Header File: cstools12.h
Import Library: cshtmv12.lib
Unicode: Implemented as Unicode and ANSI versions

See Also