| |
| BOOL Create( |
| |
LPCTSTR lpszUrl |
|
| ); |
| BOOL Create( |
| |
LPCTSTR lpszTitle, |
|
| |
DWORD dwOptions, |
|
| |
LPCTSTR lpszDataFolder |
|
| ); |
| BOOL Create( |
| |
LPCTSTR lpszTitle, |
|
| |
DWORD dwStyle, |
|
| |
LPRECT lpPosition, |
|
| |
DWORD dwOptions, |
|
| |
LPCTSTR lpszUrl, |
|
| |
LPCTSTR lpszLanguage, |
|
| |
LPCTSTR lpszDataFolder |
|
| ); |
The Create method creates a new window which hosts an instance
of the browser control.
Parameters
- lpszTitle
- A null-terminated string which specifies the text displayed in
the title bar. This parameter may be NULL or an empty string, in
which case the title bar is set to the title of the document
currently being displayed in the browser and will be automatically
updated with subsequent navigations.
- dwStyle
- An unsigned integer which specifies the window style. This is
the same windows style used with the Create function.
If the value is zero, it will default to using the
WS_OVERLAPPEDWINDOW style which creates an overlapped
window with a caption, system menu and a minimize and maximize button.
Some style bitflags will be ignored, such as the WS_CHILD
style which cannot be applied to this window. This method can
only be used to create an application window.
- lpPosition
- A pointer to a RECT structure which defines the position
and size of the window. If all structure member values are
>= 0,
their values are passed directly to Create. If the
top or left values are -1, a default position will be used. For example,
if the structure is defined as { -1, -1, 800, 600 } it
would create an 800 x 600 window at a default position on the display.
If the left or right values are -1, default values are used for the
width or height. If all values are negative, the position and size
of the window will use default values. If this parameter is NULL,
the window will be positioned in the center of the current display
with a width and height set to half the display area.
- 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 window has been
created. 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
This method creates a top-level host window and a WebView runtime
on a dedicated UI thread owned by the library. It returns after the
window and control have been created and any navigation to the initial
URL proceeds asynchronously. The returned window handle can be managed
with normal Win32 APIs.
This method requires the single-threaded apartment (STA) COM
model. During initialization the library calls CoInitializeEx as
needed and if your process has already initialized COM as MTA
(COINIT_MULTITHREADED), a browser instance cannot be
created. 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 you have created.
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 using the Detach method. 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.
Event callbacks are invoked on the thread that owns the browser
window, not the thread that calls Create. This is
typically the internal UI thread that runs the message loop for the
control. Avoid updating shared globals from both your main thread and
the browser thread without synchronization. If you need to communicate
back to your main UI, use PostMessage or SendMessage to
send application-defined messages to the window, or use an event,
critical section, or message queue rather than directly changing the
shared state.
The method can be used from a console application. You do not
need to create a message pump on your main thread; the library's
hosting thread runs the necessary loop for the browser window. GUI
applications can also call this method to create a modeless browser
window that you control like any other top-level window.
Example
#include "cstools12.h"
#include <stdio.h>
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 _tmain(int argc, TCHAR *argv[])
{
if (!WebViewInitialize(CSTOOLS12_LICENSE_KEY, NULL))
{
_tprintf(_T("Unable to initialize the WebView API, error 0x%08lx\n"), WebViewGetLastError());
return 1;
}
LPCTSTR pszAppTitle = _T("MyWebView");
LPCTSTR pszInitialUrl = _T("https://example.com");
LPCTSTR pszDataFolder = _T("MyTestApp");
DWORD dwOptions = WEBVIEW_OPTION_ENABLE_DEFAULT;
RECT rcPos = { -1, -1, 1200, 800 };
CWebView webViewer;
BOOL bCreated = webViewer.Create(
pszAppTitle,
WS_OVERLAPPEDWINDOW,
&rcPos,
dwOptions,
pszInitialUrl,
NULL,
pszDataFolder);
if (!bCreated)
{
_tprintf(_T("Unable to create a WebView window\n"));
return 2;
}
webView.EnableEvents(WebViewEvents, reinterpret_cast<DWORD_PTR>(&webView));
TCHAR szCmdLine[1024];
TCHAR *pszCmd;
TCHAR *pszArg;
while (pszCmd = _getts_s(szCmdLine, _countof(szCmdLine)))
{
while (*pszCmd && _istspace(*pszCmd))
pszCmd++;
pszArg = _tcschr(pszCmd, _T(' '));
if (pszArg)
*pszArg++ = TCHAR('\0');
if (_tcsicmp(pszCmd, _T("url")) == 0)
{
if (pszArg && _tcslen(pszArg) > 0)
{
if (!webViewer.Navigate(WEBVIEW_NAVIGATE_DEFAULT, pszArg))
{
DWORD dwError = webViewer.GetLastError();
_tprintf(_T("Navigate failed with error 0x%08lx\n"), dwError);
}
}
else
{
_tprintf(_T("This command requires a URL\n"));
}
}
else if (_tcsicmp(pszCmd, "quit") == 0)
{
break;
}
}
webViewer.Close();
webViewer.WaitUntilClosed(INFINITE);
return 0;
}
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
|
|