需求描述:
无论主窗口被拖至何处,子窗口被打开时都相对于主窗口出现。
1. 子窗口位于主窗口所在屏幕的最右侧最上方
实现效果图
实现代码
//获取主窗口bounds
const { width:mainWidth, height:mainHeight, x:mainX, y:mainY } = windows.mainWindow.getBounds();
//获取距离主窗口最近的一个屏幕id(即获取主窗口所在的屏幕id)
const nearestScreenId = screen.getDisplayNearestPoint({
x: mainX,
y: mainY
})?.id
//遍历所有屏幕,累加至距离主窗口所在的屏幕宽度
let totalWidth = 0;
for(let i = 0 ; i < screen.getAllDisplays().length; i++){
const item = screen.getAllDisplays()[i];
totalWidth += item.bounds.width;
if(nearestScreenId === item.id){
break
}
}
//计算出 x 等于 主窗口所在屏幕的右侧
let x = totalWidth - childWidth;
let y = 0;
2. 子窗口位于主窗口所在屏幕的最左侧最上方
实现效果图
实现代码
//获取距离主窗口最近的一个屏幕id(即获取主窗口所在的屏幕id)
let nearestScreenId = screen.getDisplayNearestPoint({
x: mainX,
y: mainY
})?.id
//遍历所有屏幕,累加至距离主窗口所在屏幕的前一个屏幕宽度
let totalWidth = 0;
for(let i = 0 ; i < screen.getAllDisplays().length; i++){
const item = screen.getAllDisplays()[i];
if(nearestScreenId === item.id){
break
}
totalWidth += item.bounds.width;
}
//计算出 x 等于 主窗口所在屏幕的前一个屏幕的宽度
let x = totalWidth;
let y = 0;
3. 子窗口位于主窗口的中心
实现效果图
实现代码
//获取主窗口bounds
const { width:mainWidth, height:mainHeight, x:mainX, y:mainY } = windows.mainWindow.getBounds();
let x = mainX + Math.floor((mainWidth - childWidth)/2);
let y = mainY + Math.floor((mainHeight - childHeight)/2);