(createWindow.ts):添加createWindow函数用于创建Electron窗口

📝(index.ts):更新文件导入注释
(ipc.ts):添加IPC事件监听函数用于打开和关闭窗口
(windows.ts):添加getWindow函数用于获取指定名称的窗口
This commit is contained in:
ruotongyu
2024-06-20 23:17:56 +08:00
parent 681063a163
commit d39cbacef5
4 changed files with 87 additions and 1 deletions

View File

@@ -0,0 +1,46 @@
import { BrowserWindow, BrowserWindowConstructorOptions, shell } from 'electron'
import { is } from '@electron-toolkit/utils'
import icon from '../../../resources/icon.png?asset'
import { join } from 'path'
export interface OptionsType extends Partial<BrowserWindowConstructorOptions>{
openDevTools?: boolean
}
export function createWindow(options: OptionsType): BrowserWindow { // Create the browser window.
const win = new BrowserWindow(Object.assign({
width: 500,
height: 350,
center: true,
show: false,
frame: false,
transparent: true,
// alwaysOnTop: true,
autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false
}
}, options))
// 如果是在开发环境下并且选项是打开开发者工具
if (is.dev && options.openDevTools) win.webContents.openDevTools()
win.on('ready-to-show', () => {
win.show()
})
win.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url)
return { action: 'deny' }
})
// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
win.loadURL(process.env['ELECTRON_RENDERER_URL'])
} else {
win.loadFile(join(__dirname, '../renderer/index.html'))
}
return win
}

View File

@@ -1,7 +1,10 @@
import { app, ipcMain } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import "./code"
// import "./code"
import "./db"
import "./windows"
import "./ipc"
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.

View File

@@ -0,0 +1,10 @@
import { ipcMain, IpcMainEvent } from "electron"
import { getWindow, WindowNameType } from "./windows"
ipcMain.on('openWindow', (_event: IpcMainEvent, name: WindowNameType) => {
getWindow(name).show()
})
ipcMain.on('closeWindow', (_event: IpcMainEvent, name: WindowNameType) => {
getWindow(name).hide()
})

View File

@@ -0,0 +1,27 @@
import { BrowserWindow } from "electron"
import { OptionsType, createWindow} from "./createWindow"
export type WindowNameType = 'search' | 'config'
export const config = {
search: {
id: 0,
options: {}
},
config: {
id: 0,
options: {}
}
} as Record<WindowNameType, {id: number, options: OptionsType }>
// createWindow({})
export const getWindow = (name: WindowNameType)=>{
// 根据id取得窗口
let win = BrowserWindow.fromId(config[name].id)
// 避免重复点击重复创建窗口
if (!win) {
win = createWindow(config[name].options)
config[name].id = win.id
}
return win
}