如何阻止 webview2 打开新的浏览器窗口而不是在浏览器内

如何阻止 webview2 打开新的浏览器窗口而不是在浏览器内

问题描述:

我想知道是否有办法阻止 webview2 组件打开浏览器窗口以胜利形式

i want to know if there is anyway of stopping the webview2 component from opening a browser window in win forms

发生了什么

我到处找都找不到,虽然我找到了,但它使用了 XAML/UWP

i looked everywhere but could not find one, i did find one though, but it used XAML/UWP

一个页面使用了 xaml 但代码不起作用,因为它的 XAML 和 im 使用 c#

one page used xaml but the code wont work because its XAML and im using c#

要阻止链接在新窗口中打开,您可以订阅 CoreWebView2_NewWindowRequested,如您所见.

To stop the link from opening in a new window, you subscribe to the CoreWebView2_NewWindowRequested as you have found out.

要做到这一点,最简单的方法是先订阅 CoreWebView2InitializationCompleted.

To do that, the easiest way is to subscribe to the CoreWebView2InitializationCompleted first.

WebView2 控件的属性窗口中,双击 CoreWebView2InitializationCompleted - 这将自动生成事件处理程序:

In properties window for the WebView2 control, double click CoreWebView2InitializationCompleted - that will auto generate the eventhandler:

现在您添加 CoreWebView2_NewWindowRequested 事件处理程序并将 e.NewWindow 设置为当前的 CoreWebView2.

Now you add the CoreWebView2_NewWindowRequested eventhandler and set e.NewWindow to the current CoreWebView2.

这是代码(假设您的 WebView2 控件称为 webView21):

Here's the code (assuming your WebView2 control is called webView21):

private void WebView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
{
    webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
}

private void CoreWebView2_NewWindowRequested(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NewWindowRequestedEventArgs e)
{
    e.NewWindow = webView21.CoreWebView2;
}

现在链接在同一个窗口中打开(您的 WebView2 控件).

Now the link opens in the same window (your WebView2 control).