Electron:不使用框架实现自定义的可拖拽标题栏
作者:互联网
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;
}
标签:control,const,自定义,win,标题栏,window,js,Electron,movingInterval 来源: https://www.cnblogs.com/rocael/p/16097307.html