screen
检索关于屏幕尺寸、显示器、光标位置等信息。
进程:主进程
此模块直到 app
模块的 ready
事件触发后才能使用。
screen
是一个 EventEmitter。
在渲染器 / DevTools 中,window.screen
是一个保留的 DOM 属性,所以编写 let { screen } = require('electron')
将不起作用。
创建一个填充整个屏幕的窗口的示例
- main.js
// 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')
}
})
此模块使用的屏幕坐标是 Point 结构。进程可用的坐标有两种:
- 物理屏幕点是显示器上的原始硬件像素。
- 设备独立像素 (DIP) 点是根据显示器的 DPI (每英寸点数) 进行缩放的虚拟屏幕点。
事件
screen
模块发出以下事件
事件:'display-added'
返回
event
事件newDisplay
Display
当 newDisplay
被添加时发出。
事件:'display-removed'
返回
event
事件oldDisplay
Display
当 oldDisplay
被移除时发出。
事件:'display-metrics-changed'
返回
event
事件display
DisplaychangedMetrics
string[]
当 display
中的一个或多个指标发生变化时发出。changedMetrics
是一个描述变化的字符串数组。可能的变化包括 bounds
、workArea
、scaleFactor
和 rotation
。
方法
screen
模块有以下方法
screen.getCursorScreenPoint()
返回 Point
鼠标指针当前的绝对位置。
返回值是一个 DIP 点,而不是屏幕物理点。
screen.getPrimaryDisplay()
返回 Display - 主显示器。
screen.getAllDisplays()
返回 Display[] - 当前可用的显示器数组。
screen.getDisplayNearestPoint(point)
point
Point
返回 Display - 最接近指定点的显示器。
screen.getDisplayMatching(rect)
rect
Rectangle
返回 Display - 与提供边界相交最密切的显示器。
screen.screenToDipPoint(point)
Windows Linux
point
Point
返回 Point
将屏幕物理点转换为屏幕 DIP 点。DPI 缩放是相对于包含该物理点的显示器执行的。
Wayland 上目前不支持 - 如果在那里使用,它将返回传入的点,没有任何更改。
screen.dipToScreenPoint(point)
Windows Linux
point
Point
返回 Point
将屏幕 DIP 点转换为屏幕物理点。DPI 缩放是相对于包含该 DIP 点的显示器执行的。
Wayland 上目前不支持。
screen.screenToDipRect(window, rect)
Windows
window
BrowserWindow | nullrect
Rectangle
返回 Rectangle
将屏幕物理矩形转换为屏幕 DIP 矩形。DPI 缩放是相对于最靠近 window
的显示器执行的。如果 window
为 null,则缩放将相对于最靠近 rect
的显示器执行。
screen.dipToScreenRect(window, rect)
Windows
window
BrowserWindow | nullrect
Rectangle
返回 Rectangle
将屏幕 DIP 矩形转换为屏幕物理矩形。DPI 缩放是相对于最靠近 window
的显示器执行的。如果 window
为 null,则缩放将相对于最靠近 rect
的显示器执行。