跳转到主内容

Custom Window Interactions

Custom draggable regions​

By default, windows are dragged using the title bar provided by the OS chrome. Apps that remove the default title bar need to use the app-region CSS property to define specific areas that can be used to drag the window. Setting app-region: drag marks a rectagular area as draggable.

It is important to note that draggable areas ignore all pointer events. For example, a button element that overlaps a draggable region will not emit mouse clicks or mouse enter/exit events within that overlapping area. Setting app-region: no-drag reenables pointer events by excluding a rectagular area from a draggable region.

To make the whole window draggable, you can add app-region: drag as body's style:

styles.css
body {
app-region: drag;
}

请注意,如果您使整个窗口都可拖拽,则必须将其中的按钮标记为不可拖拽,否则用户将无法点击它们:

styles.css
button {
app-region: no-drag;
}

If you're only setting a custom title bar as draggable, you also need to make all buttons in title bar non-draggable.

提示:禁用文本选择​

创建可拖拽区域时,拖拽行为可能与文本选择相冲突。 For example, when you drag the title bar, you may accidentally select its text contents. 为了避免这种情况,您需要在可拖拽区域中禁用文本选择,像这样:

.titlebar {
user-select: none;
app-region: drag;
}

提示:禁用上下文菜单​

在某些平台上, 可拖拽区域将被视为non-client frame, 因此当您右键单击它时, 系统菜单将弹出。 要使上下文菜单在所有平台上都正确运行, 您永远也不要在可拖拽区域上使用自定义上下文菜单。

Click-through windows​

To create a click-through window, i.e. making the window ignore all mouse events, you can call the win.setIgnoreMouseEvents(ignore) API:

main.js
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.setIgnoreMouseEvents(true)

Forward mouse events macOS Windows​

忽略鼠标消息会使网页内容无视鼠标移动,这意味着鼠标移动事件不会被发出。 On Windows and macOS, an optional parameter can be used to forward mouse move messages to the web page, allowing events such as mouseleave to be emitted:

main.js
const { BrowserWindow, ipcMain } = require('electron')
const path = require('node:path')

const win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})

ipcMain.on('set-ignore-mouse-events', (event, ignore, options) => {
const win = BrowserWindow.fromWebContents(event.sender)
win.setIgnoreMouseEvents(ignore, options)
})
preload.js
window.addEventListener('DOMContentLoaded', () => {
const el = document.getElementById('clickThroughElement')
el.addEventListener('mouseenter', () => {
ipcRenderer.send('set-ignore-mouse-events', true, { forward: true })
})
el.addEventListener('mouseleave', () => {
ipcRenderer.send('set-ignore-mouse-events', false)
})
})

This makes the web page click-through when over the #clickThroughElement element, and returns to normal outside it.