任务栏的进度条 (Windows, macOS, Unity)

概览

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

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

Windows 进度条

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

macOS 进度条

在Linux系统中,Unity桌面也有相似的特性,能在Launcher上显示进度条。

Linux 进度条

注意:在 Windows 上,每个窗口都可以有自己的进度条,而在 macOS 和 Linux(unity桌面)上,同一个应用程序只能有一个进度条。


这三种环境中的进度条功能由同一个API实现:BrowserWindow实例下的setProgressBar()方法。 此方法以介于 01 之间的小数表示进度。 例如,如果有一个耗时很长的任务,它当前的进度是63%,那么你可以用setProgressBar(0.63)来显示这一进度。

Setting the parameter to negative values (e.g. -1) will remove the progress bar. Setting it to a value greater than 1 will indicate an indeterminate progress bar in Windows or clamp to 100% in other operating systems. An indeterminate progress bar remains active but does not show an actual percentage, and is used for situations when you do not know how long an operation will take to complete.

参见 API documentation for more options and modes

示例

In this example, we add a progress bar to the main window that increments over time using Node.js timers.

  1. const { app, BrowserWindow } = require('electron')
  2. let progressInterval
  3. function createWindow () {
  4. const win = new BrowserWindow({
  5. width: 800,
  6. height: 600
  7. })
  8. win.loadFile('index.html')
  9. const INCREMENT = 0.03
  10. const INTERVAL_DELAY = 100 // ms
  11. let c = 0
  12. progressInterval = setInterval(() => {
  13. // update progress bar to next value
  14. // values between 0 and 1 will show progress, >1 will show indeterminate or stick at 100%
  15. win.setProgressBar(c)
  16. // increment or reset progress bar
  17. if (c < 2) c += INCREMENT
  18. else c = 0
  19. }, INTERVAL_DELAY)
  20. }
  21. app.whenReady().then(createWindow)
  22. // before the app is terminated, clear both timers
  23. app.on('before-quit', () => {
  24. clearInterval(progressInterval)
  25. })
  26. app.on('window-all-closed', () => {
  27. if (process.platform !== 'darwin') {
  28. app.quit()
  29. }
  30. })
  31. app.on('activate', () => {
  32. if (BrowserWindow.getAllWindows().length === 0) {
  33. createWindow()
  34. }
  35. })

After launching the Electron application, the dock (macOS) or taskbar (Windows, Unity) should show a progress bar that starts at zero and progresses through 100% to completion. It should then show indeterminate (Windows) or pin to 100% (other operating systems) briefly and then loop.

macOS dock 进度条

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

macOS Mission Control 进度条