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; }