Skip to main content

在浏览器窗口中表示文件

¥Representing Files in a BrowserWindow

概述

¥Overview

在 macOS 上,你可以为应用中的任何窗口设置表示文件。所代表的文件的图标将显示在标题栏中,当用户 Command-ClickControl-Click 时,将显示一个带有文件路径的弹出窗口。

¥On macOS, you can set a represented file for any window in your application. The represented file's icon will be shown in the title bar, and when users Command-Click or Control-Click, a popup with a path to the file will be shown.

Represented File

注意:上面的屏幕截图是一个示例,其中此功能用于指示 Atom 文本编辑器中当前打开的文件。

¥NOTE: The screenshot above is an example where this feature is used to indicate the currently opened file in the Atom text editor.

你还可以设置窗口的编辑状态,以便文件图标可以指示该窗口中的文档是否已被修改。

¥You can also set the edited state for a window so that the file icon can indicate whether the document in this window has been modified.

要设置窗口的代表文件,可以使用 BrowserWindow.setRepresentedFilenameBrowserWindow.setDocumentEdited API。

¥To set the represented file of window, you can use the BrowserWindow.setRepresentedFilename and BrowserWindow.setDocumentEdited APIs.

示例

¥Example

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

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

win.setRepresentedFilename(os.homedir())
win.setDocumentEdited(true)

win.loadFile('index.html')
}

app.whenReady().then(() => {
createWindow()

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

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

启动 Electron 应用后,按下 CommandControl 键单击标题。你应该会看到一个弹出窗口,顶部显示所表示的文件。在本指南中,这是当前用户的主目录:

¥After launching the Electron application, click on the title with Command or Control key pressed. You should see a popup with the represented file at the top. In this guide, this is the current user's home directory:

Represented file