Electron:不使用框架實現自定義的可拖拽標題欄
阿新 • • 發佈:2022-04-04
preload.js:
contextBridge.exposeInMainWorld('window_control', {
toClose: () => ipcRenderer.send('close-app'),
toMinimize: () => ipcRenderer.send('min-app'),
windowMove: (canMove) => ipcRenderer.send("window-move-open", canMove)
})
最小化
renderer.js
document.querySelector(".my-btn-minimize").addEventListener('click', () => { window.window_control.toMinimize() })
main.js
ipcMain.on('min-app', () => {
if(win){
win.minimize()
}
})
最大化同理
關閉視窗
renderer.js
document.querySelector(".my-btn-close").addEventListener('click', () => {
window.window_control.toClose()
})
main.js
ipcMain.on('close-app', () => { if(win) { win.close() } })
拖拽視窗
randerer.js
function titleDown(e) {
window.window_control.windowMove(true)
}
function titleUp(e){
window.window_control.windowMove(false)
}
main.js
ipcMain.on("window-move-open", (events, canMoving) => { if (canMoving) { // 讀取原位置 const winPosition = win.getPosition(); winStartPosition = { x: winPosition[0], y: winPosition[1] }; mouseStartPosition = screen.getCursorScreenPoint(); // 清除 if (movingInterval) { clearInterval(movingInterval); } // 新開 movingInterval = setInterval(() => { // 實時更新位置 const cursorPosition = screen.getCursorScreenPoint(); const x = winStartPosition.x + cursorPosition.x - mouseStartPosition.x; const y = winStartPosition.y + cursorPosition.y - mouseStartPosition.y; win.setPosition(x, y, true); }, 10); } else { clearInterval(movingInterval); movingInterval = null; } });
setInterval函式的第二個引數,也就是定時器間隔,會直接決定拖拽視窗的流暢感,但是如果設定太低……會出問題!
使標題欄內容不可選擇
style.css
.my-title {
-webkit-user-select: none;
}