截取WebView2中的TAB键

问题描述

我想在Webview2中拦截Tab键。

我通过ICoreWebView2AcceleratorKeyPressedEventHandler注册的add_AcceleratorKeyPressed可以拦截许多功能键

但是某些键(例如光标键和TAB键)不会调用此事件处理程序。与F5键相同,它缝接了一些键是保留的,这很奇怪,因为位置键up,down,pos1,end可以被截获。

因为WebView2本身的窗口位于另一个进程中,所以我没有机会使用标准子类化,并且我想避免使用钩子进行子类化。

解决方法

正如讨论中提到的,我解决了这个问题。

首先,我将Java脚本注入浏览器

m_spWebView->AddScriptToExecuteOnDocumentCreated(
    L"window.document.addEventListener('keydown',function(e) {\n"
    L" if (e.keyCode===9 || e.keyCode===13) {\n"
    L"  window.chrome.webview.postMessage('" CHAR_TOKEN L"'+e.keyCode.toString()); \n"
    L"  e.preventDefault(); \n"
    L"}});\n",Callback<ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler>(this,&CBrowserWV2Wnd::OnAddScriptToExecuteOnDocumentCreated).Get()
);

然后我添加了ICoreWebView2WebMessageReceivedEventHandleradd_WebMessageReceived来处理来自托管WebView2的适当消息。

LPWSTR pwStr = nullptr;
args->TryGetWebMessageAsString(&pwStr);
if (_wcsnicmp(pwStr,CHAR_TOKEN,MfxCountOf(CHAR_TOKEN)-1)==0)
{
    // Get the Keycode from the message
    auto iChar = wcstol(pwStr+MfxCountOf(CHAR_TOKEN)-1,nullptr,10);
    // Do something with the intercepted character
    ...
}
::CoTaskMemFree(pwStr);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...