const { app, BrowserWindow, Menu, ipcMain, globalShortcut, dialog, shell } = require('electron'); const path = require('path') const { createWriteStream, existsSync } = require('fs'); const request = require('request'); let win, loadingWin; Menu.setApplicationMenu(null) // 去掉菜单栏 app.commandLine.appendSwitch('wm-window-animations-disabled') // 拖动闪屏 /** 打开下载选择路径 */ async function openFileDialog(oldPath = app.getPath('downloads')) { if (oldPath) return oldPath const { canceled, filePaths } = await dialog.showOpenDialog(this.win, { title: '选择保存位置', properties: ['openDirectory', 'createDirectory'], defaultPath: oldPath, }) return !canceled ? filePaths[0] : oldPath } /** * 下载 * @param url 下载地址 */ async function downloadFile(url) { const filePath = await this.openFileDialog() // FN2 // this.win.webContents.downloadURL(url); // this.win.webContents.session.once('will-download', async (event, item, webContents) => { // const path = await this.openFileDialog() // const filePath = path.join(path,`${filename}`) // }) // FN1 const res = await new Promise((res, rej) => { const stream = request(url).pipe(createWriteStream(filePath)) stream.on('finish', res(true)) stream.on('error', rej(false)) }) dialog.showMessageBox(this.win, { message: res ? '下载成功' : '下载失败' }) } /** 打开文件夹 */ function openFileInFolder(path) { if (!existsSync(path)) return false shell.showItemInFolder(path) return true } // 创建loading 窗口 const showLoading = () => { loadingWin = new BrowserWindow({ frame: false, // 无边框(窗口、工具栏等),只包含网页内容 width: 200, height: 200, resizable: false, center: true, alwaysOnTop: true, transparent: true // 窗口是否支持透明,如果想做高级效果最好为true }) loadingWin.loadFile('loading.html') loadingWin.on('close', () => { loadingWin = null }) } // 创建主程序 窗口 const createWindow = () => { win = new BrowserWindow({ minWidth: 1620, minHeight: 900, webPreferences: { contextIsolation: true, nodeIntegration: true, webSecurity: false, preload: path.join(__dirname, './preload.js') }, show: false })// 创建一个窗口 // 不同环境加载不同文件 if (app.isPackaged) { win.loadFile('dist/index.html') } else { win.loadURL('http://localhost:6547/') } // 事件监听 win.on('close', () => { // 回收BrowserWindow对象 win = null }) } // 事件监听 app.on('ready', async () => { showLoading() createWindow() // 监听渲染进行 ipcMain.once('close-loading', () => { loadingWin.close() win.show() }) // 在BrowserWindow创建完成后,注册全局快捷键 globalShortcut.register('Control+F12', () => { win.webContents.toggleDevTools() }) }) app.on('window-all-closed', () => { app.quit() }) app.on('activate', () => { if (win == null) { createWindow() } })