跳到主要内容

screen

获取有关屏幕尺寸、显示器、光标位置等信息。

进程: 主进程

此模块必须在 app 模块的 ready 事件触发后才能使用。

screen 是一个 EventEmitter

注意: 在渲染器进程 / DevTools 中,window.screen 是一个保留的 DOM 属性,因此编写 let { screen } = require('electron') 将不起作用。

创建一个填充整个屏幕的窗口的例子

// Retrieve information about screen size, displays, cursor position, etc.
//
// For more info, see:
// https://electron.js.cn/docs/latest/api/screen

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

let mainWindow = null

app.whenReady().then(() => {
// Create a window that fills the screen's available work area.
const primaryDisplay = screen.getPrimaryDisplay()
const { width, height } = primaryDisplay.workAreaSize

mainWindow = new BrowserWindow({ width, height })
mainWindow.loadURL('https://electron.js.cn')
})

另一个在外部显示器中创建窗口的例子

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

let win

app.whenReady().then(() => {
const displays = screen.getAllDisplays()
const externalDisplay = displays.find((display) => {
return display.bounds.x !== 0 || display.bounds.y !== 0
})

if (externalDisplay) {
win = new BrowserWindow({
x: externalDisplay.bounds.x + 50,
y: externalDisplay.bounds.y + 50
})
win.loadURL('https://github.com')
}
})

事件

screen 模块触发以下事件

事件: 'display-added'

返回

当添加了 newDisplay 时触发。

事件: 'display-removed'

返回

oldDisplay 被移除时触发。

事件: 'display-metrics-changed'

返回

  • event Event
  • display Display
  • changedMetrics string[]

display 中的一个或多个指标发生变化时触发。changedMetrics 是一个描述变化的字符串数组。可能的变化包括 boundsworkAreascaleFactorrotation

方法

screen 模块有以下方法

screen.getCursorScreenPoint()

返回 Point

鼠标指针当前的绝对位置。

注意: 返回值是 DIP 点,不是屏幕物理点。

screen.getPrimaryDisplay()

返回 Display - 主显示器。

screen.getAllDisplays()

返回 Display[] - 当前可用的显示器数组。

screen.getDisplayNearestPoint(point)

返回 Display - 距离指定点最近的显示器。

screen.getDisplayMatching(rect)

返回 Display - 与提供的边界最接近交叉的显示器。

screen.screenToDipPoint(point) Windows

返回 Point

将屏幕物理点转换为屏幕 DIP 点。DPI 缩放是相对于包含物理点的显示器进行的。

screen.dipToScreenPoint(point) Windows

返回 Point

将屏幕 DIP 点转换为屏幕物理点。DPI 缩放是相对于包含 DIP 点的显示器进行的。

screen.screenToDipRect(window, rect) Windows

返回 Rectangle

将屏幕物理矩形转换为屏幕 DIP 矩形。DPI 缩放是相对于离 window 最近的显示器进行的。如果 window 为 null,则缩放将相对于离 rect 最近的显示器进行。

screen.dipToScreenRect(window, rect) Windows

返回 Rectangle

将屏幕 DIP 矩形转换为屏幕物理矩形。DPI 缩放是相对于离 window 最近的显示器进行的。如果 window 为 null,则缩放将相对于离 rect 最近的显示器进行。