C#transparencyKey将webview2的背景变透明
时间: 2023-07-12 16:21:22 浏览: 88
您可以按照以下步骤来将Webview2的背景变成透明:
1. 在您的代码中,设置Webview2的父控件的TransparencyKey属性为与Webview2控件背景颜色相同的颜色,例如: Color.Fuchsia。
2. 在Webview2控件的属性中,将IsWebMessageEnabled属性设置为True。
3. 在Webview2控件的事件中添加以下代码:
```
private void webView21_CoreWebView2Ready(object sender, EventArgs e)
{
webView21.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.getComputedStyle(document.body).backgroundColor);");
}
private async void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
if (e.TryGetWebMessageAsString(out string backgroundColor))
{
await webView21.CoreWebView2.ExecuteScriptAsync($"document.body.style.backgroundColor = '{backgroundColor}';");
this.BackColor = Color.Fuchsia;
}
}
```
这将获取Webview2控件的背景颜色,并将其设置为父控件的TransparencyKey属性值,从而实现透明背景效果。