electron 按住ctrl时显示小窗口窗口位置在鼠标同时如果点击其他地方这个窗口就消失
这是一个比较常见的需求,可以通过以下步骤来实现:
- 监听鼠标按下事件,当按下ctrl键的同时,创建一个小窗口,并将其位置设置为鼠标位置。
- 监听鼠标移动事件,当ctrl键依然被按下时,不断更新小窗口的位置为鼠标位置。
- 监听鼠标松开事件,当ctrl键被松开时,如果小窗口存在,则移除小窗口。
- 监听鼠标点击事件,当小窗口存在时,如果点击的不是小窗口,则移除小窗口。
以下是一个示例代码:
const { app, BrowserWindow } = require('electron')
let win, overlayWin
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
// 监听按下ctrl键事件
win.on('keydown', (event) => {
if (event.ctrlKey) {
// 创建小窗口
overlayWin = new BrowserWindow({
width: 200,
height: 100,
frame: false,
transparent: true,
alwaysOnTop: true,
webPreferences: {
nodeIntegration: true
}
})
overlayWin.loadFile('overlay.html')
// 设置小窗口位置为鼠标位置
const { x, y } = win.webContents.getCursorScreenPoint()
overlayWin.setPosition(x, y)
}
})
// 监听鼠标移动事件
win.on('mousemove', (event) => {
if (overlayWin && event.ctrlKey) {
// 更新小窗口位置为鼠标位置
const { x, y } = win.webContents.getCursorScreenPoint()
overlayWin.setPosition(x, y)
}
})
// 监听松开ctrl键事件
win.on('keyup', (event) => {
if (event.key === 'Control' && overlayWin) {
// 移除小窗口
overlayWin.destroy()
overlayWin = null
}
})
// 监听鼠标点击事件
win.on('click', (event) => {
if (overlayWin && !overlayWin.isDestroyed() && !overlayWin.getBounds().contains(event.x, event.y)) {
// 移除小窗口
overlayWin.destroy()
overlayWin = null
}
})
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
在上面的示例代码中,我们监听了窗口的keydown、mousemove、keyup和click事件,分别用来创建小窗口、更新小窗口位置、移除小窗口和判断是否需要移除小窗口。其中,小窗口的创建和移除使用了BrowserWindow类,通过设置frame、transparent和alwaysOnTop属性来去除窗口边框、使窗口透明、将窗口置于顶层。小窗口的内容可以通过loadFile或loadURL方法加载一个html文件或url地址。具体实现可以根据自己的需求进行调整
原文地址: https://www.cveoy.top/t/topic/fV0z 著作权归作者所有。请勿转载和采集!