跳转到主内容

进度条

概览​

进度条使窗口能够向用户提供其进度信息,而无需被切换到前台。

在Windows环境下,进度条被显示在任务栏按钮上。

Windows 进度条

在MacOS环境下,进度条将被显示在dock栏图标上

macOS 进度条

NOTE: on Windows, each window can have its own progress bar, whereas on macOS there can be only one progress bar for the application. On Linux, progress bars are not supported.


以上这三种情况都使用相同的 API 来实现 - 即 BrowserWindow 实例上的 setProgressBar() 方法。此方法以介于 0 和 1 之间的小数表示进度。例如,如果有一个耗时很长的任务,它当前的进度是63%,那么你可以用setProgressBar(0.63)来显示这一进度。

将参数设置为负值 (例如, -1) 将删除progress bar。设定值大于 1 在 Windows 中将表示一个不确定的进度条 ,或在其他操作系统中显示为 100%。一个不确定的progress bar 仍然处于活动状态,但不显示实际百分比, 并且用于当 您不知道一个操作需要多长时间才能完成的情况。

参阅 API 文档以获取更多选项和模式。

示例​

在此示例中,我们将进度栏添加到main window中,该窗口会使用node.js的计时器实现随着时间的推移而进度增长。

const { app, BrowserWindow } = require('electron/main')

let progressInterval

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})

win.loadFile('index.html')

const INCREMENT = 0.03
const INTERVAL_DELAY = 100 // ms

let c = 0
progressInterval = setInterval(() => {
// update progress bar to next value
// values between 0 and 1 will show progress, >1 will show indeterminate or stick at 100%
win.setProgressBar(c)

// increment or reset progress bar
if (c < 2) {
c += INCREMENT
} else {
c = (-INCREMENT * 5) // reset to a bit less than 0 to show reset state
}
}, INTERVAL_DELAY)
}

app.whenReady().then(createWindow)

// before the app is terminated, clear both timers
app.on('before-quit', () => {
clearInterval(progressInterval)
})

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})

After launching the Electron application, the dock (macOS) or taskbar (Windows) should show a progress bar that starts at zero and progresses through 100% to completion. 应该显示不确定的 (Windows) 或短暂的固定到100% (其他操作系统) 并然后循环。

macOS dock 进度条

对于macOS,当使用 Mission Control 时,应用程序也会显示进度条

macOS Mission Control 进度条