如何自定义Electron应用程序的窗口标题栏?

qf9go6mv  于 2023-05-27  发布在  Electron
关注(0)|答案(3)|浏览(1014)

我开始使用Electron构建桌面应用程序。如何自定义窗口标题栏(包含关闭、最小化和全屏按钮)以添加自定义视图?Safari是我想到的一个例子:

oknrviil

oknrviil1#

在Electron中,您唯一的选择是创建一个frameless(又名无边框)窗口,然后使用CSS创建一个“假”标题栏,包括您需要的任何UI元素。
Electron/webkit提供了CSS属性,允许您将任何元素设置为可拖动的,例如标题栏:

.titlebar {
  -webkit-user-select: none;
  -webkit-app-region: drag;
}
izj3ouym

izj3ouym2#

第一个跨平台选项是创建一个frameless window。第二个仅适用于macOS,允许您隐藏标题栏,但保留窗口控件,允许添加自定义按钮。示例:

const { BrowserWindow } = require('electron')

// This will create a window without titlebar, allowing for customization
let win = new BrowserWindow({ titleBarStyle: 'hidden' })
win.show()

然后你可以使用css属性-webkit-user-select-webkit-app-region来指定拖动区域。

fcy6dtqo

fcy6dtqo3#

通过创建无框架窗口隐藏默认标题栏:

// main.js
window = new BrowserWindow({
    titlebarStyle: 'hidden',
    trafficLightPosition: {
        x: 15,
        y: 13,  // macOS traffic lights seem to be 14px in diameter. If you want them vertically centered, set this to `titlebar_height / 2 - 7`.
    },
})

然后使用HTML + CSS创建自己的临时标题栏:

<!-- index.html -->
<body>
    <header class="titlebar"></header>
    ...
</body>
/* styles.css */
.titlebar {
    background-color: #f0f0f0;
    height: 40px;
    border-bottom: 1px solid #d0d0d0;
    -webkit-app-region: drag;    /* Allow user to drag the window using this titlebar */
    -webkit-user-select: none;   /* Prevent user from selecting things */
    user-select: none;
}

目前的结果:

**请注意,标题栏显示在滚动条下方。当用户滚动时,它甚至会移动。**我们需要将它与可滚动内容分开,方法是将标题栏下面的所有内容 Package 在<div class="main-content">中,然后添加以下样式:

.main-content {
    height: calc(100vh - 40px);  /* Force the content to take up the viewport height minus the titlebar height */
    overflow: auto;              /* Allow the main content to be scrollable */
}
body {
    overflow: hidden;            /* Make the HTML body be non-scrollable */
}

最终结果:

现在你可以在上面添加任何你想要的HTML内容。

相关问题