Electron 進(jìn)度條

2023-02-16 17:15 更新

概覽?

進(jìn)度條使窗口能夠向用戶提供其進(jìn)度信息,而無(wú)需被切換到前臺(tái)。

在Windows環(huán)境下,進(jìn)度條被顯示在任務(wù)欄按鈕上。


在MacOS環(huán)境下,進(jìn)度條將被顯示在dock欄圖標(biāo)上


在Linux系統(tǒng)中,Unity桌面也有相似的特性,能在Launcher上顯示進(jìn)度條。


注意:在 Windows 上,每個(gè)窗口都可以有自己的進(jìn)度條,而在 macOS 和 Linux(unity桌面)上,同一個(gè)應(yīng)用程序只能有一個(gè)進(jìn)度條。

這三種環(huán)境中的進(jìn)度條功能由同一個(gè)API實(shí)現(xiàn):BrowserWindow實(shí)例下的setProgressBar()方法。 此方法以介于 0 和 1 之間的小數(shù)表示進(jìn)度。 例如,如果有一個(gè)耗時(shí)很長(zhǎng)的任務(wù),它當(dāng)前的進(jìn)度是63%,那么你可以用setProgressBar(0.63)來(lái)顯示這一進(jìn)度。

將參數(shù)設(shè)置為負(fù)值 (例如, -1) 將刪除progress bar。 設(shè)定值大于 1 在 Windows 中將表示一個(gè)不確定的進(jìn)度條 ,或在其他操作系統(tǒng)中顯示為 100%。 一個(gè)不確定的progress bar 仍然處于活動(dòng)狀態(tài),但不顯示實(shí)際百分比, 并且用于當(dāng) 您不知道一個(gè)操作需要多長(zhǎng)時(shí)間才能完成的情況。

示例?

在此示例中,我們將進(jìn)度欄添加到main window中,該窗口會(huì)使用node.js的計(jì)時(shí)器實(shí)現(xiàn)隨著時(shí)間的推移而進(jìn)度增長(zhǎng)。

 main.js index.html 
const { app, BrowserWindow } = require('electron')

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()
  }
})
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
    <h1>Hello World!</h1>
    <p>Keep an eye on the dock (Mac) or taskbar (Windows, Unity) for this application!</p>
    <p>It should indicate a progress that advances from 0 to 100%.</p>
    <p>It should then show indeterminate (Windows) or pin at 100% (other operating systems)
      briefly and then loop.</p>
</body>
</html>

DOCS/FIDDLES/FEATURES/PROGRESS-BAR (22.0.3)

Open in Fiddle

啟動(dòng) Electron 應(yīng)用程序后,Dock (macOS) 或 taskbar (Windows, Unity) 應(yīng)該顯示一個(gè)進(jìn)度條, 從零開始, 到100%到完成。 應(yīng)該顯示不確定的 (Windows) 或短暫的固定到100% (其他操作系統(tǒng)) 并然后循環(huán)。


對(duì)于macOS,當(dāng)使用 Mission Control 時(shí),應(yīng)用程序也會(huì)顯示進(jìn)度條



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)