首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Win32 WebView2将不会聚焦HTML

Win32 WebView2将不会聚焦HTML
EN

Stack Overflow用户
提问于 2022-07-16 03:44:28
回答 2查看 324关注 0票数 0

我很难集中WebView2启动时加载的HTML。我尝试过从web文档中聚焦JS,在C++界面和HTML之间来回切换--似乎什么都不起作用。只有当某些“动作”发生时,窗口才会聚焦,比如弹出一个警报对话框。我本来希望利用C++的强大功能,并将其集成到轻量级原生浏览器客户机中,但现在证明这是相当困难的。我很想知道为什么会发生这种事。我已经共享了两段代码,一个是WebView2实现的代码,另一个是一个在正常情况下关注的示例html文件。请不要忘记HTML路径到您的自定义一个,我已经标记出来,为您的方便。

  • 为大量的代码事先道歉,我不知道我们是否能够在这里折叠代码。微软用12行代码编写了一个函数原型。有时很迷茫。
  • 如果您不使用Visual,我已经创建了一个脚本,以便我们仍然能够编译和测试代码(以.bat文件的形式运行):
代码语言:javascript
复制
@echo off
cl /EHsc /GR /FI"iso646.h" /Zc:strictStrings /we4627 /we4927 /wd4351 /W4 /D"_CRT_SECURE_NO_WARNINGS" /nologo /D_UNICODE /DUNICODE /DWIN32 /D_WINDOWS /c /Ipath\to\webview2\include /Ipath\to\winrt\include webweb.cpp&^
link webweb.obj WebView2Loader.dll.lib /subsystem:windows user32.lib&^
webweb.exe
pause
  • 用于测试的示例WebView2代码。
代码语言:javascript
复制
#include <windows.h>
#include <stdlib.h>
#include <string>
#include <tchar.h>
#include <wrl.h>
#include <wil/com.h>
// include WebView2 header
#include "WebView2.h"

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[] = _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> webviewWindow;

int CALLBACK WinMain(
    _In_ HINSTANCE hInstance,
    _In_ HINSTANCE hPrevInstance,
    _In_ LPSTR     lpCmdLine,
    _In_ int       nCmdShow
)
{
    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, IDI_APPLICATION);
    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;

    int dispw = GetSystemMetrics(SM_CXSCREEN);
    int disph = GetSystemMetrics(SM_CYSCREEN);
    int windw = dispw / 2;
    int windh = disph / 2;
    int x = (dispw - windw) / 2;
    int y = (disph - windh) / 2;

    // 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,
        x, y,
        windw, windh,
        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
    CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
        Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
            [hWnd](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](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
                        if (controller != nullptr) {
                            webviewController = controller;
                            webviewController->get_CoreWebView2(&webviewWindow);
                        }
                        // Add a few settings for the webview
                        // The demo step is redundant since the values are the default settings
                        ICoreWebView2Settings* Settings;
                        webviewWindow->get_Settings(&Settings);
                        Settings->put_IsScriptEnabled(TRUE);
                        Settings->put_AreDefaultScriptDialogsEnabled(FALSE);
                        Settings->put_IsWebMessageEnabled(FALSE);
                        RECT bounds;
                        GetClientRect(hWnd, &bounds);
                        webviewController->put_Bounds(bounds);
                        webviewWindow->AddScriptToExecuteOnDocumentCreated(L"text.setValue('ayee');", NULL);

                        
                        
webviewWindow->Navigate(L"file:///path/to/test.html");  



                        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;
}
  • 用于测试的示例HTML文件
代码语言:javascript
复制
<!DOCTYPE HTML>
<HTML>
<HEAD>
<STYLE>
body
{
    display: flex;
    width: 100vw;
    overflow: none;
    scrollbar: none;
    align-items: center;
    justify-content: center;
}
#textarea
{
    width: 400px;
    height: 400px;
    resize: none;
    overflow:auto;
}
</STYLE>
<TITLE>EXAMPLE</TITLE>
</HEAD>
<BODY>
<textarea ID="textpane"></textarea>
<SCRIPT>
var te = document.getElementById('textpane');
window.onload = function()
{
    te.focus();
}
</SCRIPT>
</BODY>
</HTML>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-22 02:36:42

在筛选了Microsoft文档之后,我们认为我们必须添加:

代码语言:javascript
复制
webviewController->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);

对于WebView组件来说,它可以自己对焦。否则,一些消息/ JS警报对话框必须与视图一起呈现,在我们退出呈现的对话框窗口后,该对话框将被聚焦。

  • Navigate()方法之后添加。
  • 在某些情况下,可能还需要显式地指示HTML内部的组件焦点。上述代码只激活WebView,HTML仍然必须决定它的哪些组件获得焦点。Win32 API窗口焦点实用程序不能工作的原因是它们处理本机窗口,并且不会将内部WebView解释为本地窗口。
票数 0
EN

Stack Overflow用户

发布于 2022-07-16 03:56:23

H库包含一个winuser.h库,该库有一个SetActiveWindow函数,下面是文档:Winuser-设置SetActiveWindow

还有SetFocus函数

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73001365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档