如何在Webview2 + WPF中使用CSS拖动样式创建无框架、可拖动的窗口



我正在将一个电子应用程序迁移到WPF + Webview2.

在我的电子应用程序中,我有无框窗口。创建一个自定义的、可拖动的标题栏相当于在我想要拖动的div上添加一个CSS属性:-webkit-app-region: drag

在下面的示例:

main.js:

const {app, BrowserWindow} = require('electron')
function createWindow () {
const mainWindow = new BrowserWindow()
mainWindow.loadFile('index.html')
mainWindow.webContents.setWindowOpenHandler(_ => {
return {
action: "allow",
overrideBrowserWindowOptions: {
frame: false
}
}
})
}
app.whenReady().then(() => {
createWindow()
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})

index . html:

<button onclick="window.open('index2.html')">Open Frameless Window</button>

index2.html:

<div style="-webkit-app-region: drag; background-color:green">Toolbar</div>
<div>Body</div>

在我的Webview2应用程序中,我有:

public static async void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
{
var obj = e.GetDeferral();
var win = new Window();
win.WindowStyle = WindowStyle.None; // remove the border
win.Show();
var w = new WebView2();
win.Content = w;
await w.EnsureCoreWebView2Async(MainWindow.Webview.CoreWebView2.Environment);

e.NewWindow = w.CoreWebView2;
obj.Complete();
}

没有边框的窗口正确显示,但自定义标题栏不可拖动。看起来好像CSS样式没有被看到。

我怎样才能使这些样式有效果?

WebView2不支持webkit-app-region: drag样式。你需要像这个GitHub问题中描述的那样手动实现可拖动区域。

如果你愿意,你可以打开我们的WebView2Feedback项目的功能请求。

仅供参考,对于那些和我经历过同样痛苦的人,WebView2现在支持这个:https://github.com/MicrosoftEdge/WebView2Feedback/issues/2243#issuecomment-1448819425

您只需要传入额外的参数--enable-features=msWebView2EnableDraggableRegions

最新更新