he wei
2022-11-13 b4816f6294646157b50bb49f1d19eaf306e0ac8c
src/background.js
@@ -3,7 +3,7 @@
import { app, protocol, BrowserWindow, ipcMain, ipcRenderer, dialog, shell, Menu, webContents } from 'electron'
import { autoUpdater } from 'electron-updater';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import path from 'path';
import child_process from 'child_process';
import log from 'electron-log';
@@ -11,6 +11,10 @@
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
let win = null;
// 调试自动升级
/**
@@ -28,11 +32,25 @@
 * 
 * 
 */
Object.defineProperty(app, 'isPackaged', {
  get() {
    return true;
  }
});
// 单例锁
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到myWindow这个窗口
    if (win) {
      if (win.isMinimized()) win.restore()
      win.focus()
      if (commandLine[2]) {
        win.webContents.send('selected-file', { filePaths: [commandLine[2]] }, 'MenuList');
      }
    }
  })
}
const remote = require('@electron/remote/main');
@@ -50,11 +68,10 @@
if (!isDevelopment) {
  Menu.setApplicationMenu(null);
}
let win;
async function createWindow() {
async function createWindow(cb) {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    width: 1000,
    height: 600,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
@@ -80,8 +97,52 @@
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
    win.webContents.openDevTools()
  }
  if (cb && 'function' == typeof cb) {
    win.once('ready-to-show', () => {
      cb(win.webContents);
    })
  }
  win.webContents.session.on('will-download', (e, item) => {
    // const filePath = path.join(saveUrl, item.getFilename());
    // item.setSavePath(filePath); // 'C:\Users\kim\Downloads\第12次.zip'
    // let value;
    // //监听下载过程,计算并设置进度条进度
    // item.on('updated', (evt, state) => {
    //   if ('progressing' === state) {
    //     //此处  用接收到的字节数和总字节数求一个比例  就是进度百分比
    //     if (item.getReceivedBytes() && item.getTotalBytes()) {
    //       value = parseInt(
    //         100 * (
    //           item.getReceivedBytes() / item.getTotalBytes()
    //         )
    //       )
    //     }
    //     // 把百分比发给渲染进程进行展示
    //     // win.webContents.send('updateProgressing', value);
    //     // mac 程序坞、windows 任务栏显示进度
    //     win.setProgressBar(value);
    //   }
    // });
    //监听下载结束事件
    item.on('done', (e, state) => {
      //如果窗口还在的话,去掉进度条
      // if (!win.isDestroyed()) {
      //   win.setProgressBar(-1);
      // }
      //下载被取消或中断了
      if (state === 'interrupted') {
        dialog.showErrorBox('下载失败', `文件 ${item.getFilename()} 因为某些原因被中断下载`);
      }
      // 下载成功后打开文件所在文件夹
      if (state === 'completed') {
        setTimeout(() => {
          shell.showItemInFolder(item.getSavePath())
        }, 1000);
      }
    });
  });
}
// Quit when all windows are closed.
@@ -103,28 +164,14 @@
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow();
  let cb = undefined;
  if (process.argv[1]) {
    cb = (sender) => {
      sender.send('selected-file', { filePaths: [process.argv[1]] }, 'MenuList');
    }
  }
  createWindow(cb);
})
// ipcMain 事件处理
// ipcMain.on('open-file-dialog', (event) => {
//   dialog.showOpenDialog({
//     properties: ['openFile', 'openDirectory']
//   }, (files) => {
//     // child_process.spawn('cmd.exe', ['/c', 'echo '+JSON.stringify(files)+' success >> 112233.txt'])
//     if(files) {
//       event.sender.send('selected-directory', files);
//     }
//   })
// });
// 所有的新开窗口事件都调用系统默认浏览器来打开页面
app.on('web-contents-created', (e, webContents) => {
@@ -155,25 +202,6 @@
  })
});
// 存在新版本时,默认自动下载更新
// autoUpdater.autoDownload = false // 若想通过渲染进程手动触发,需要设置autoDownload为false
// 当更新发生错误的时候触发
// autoUpdater.on('error', (err) => {})
// // 当开始检查更新的时候触发
// autoUpdater.on('checking-for-update', (event, arg) => {}) // 通知渲染进程,此时开始检测版本
// // 发现可更新版本时触发
// autoUpdater.on('update-available', (info) => {}) // 发现可更新版本-弹层询问渲染进程是否需要“立即更新”
// // 没有可更新版本时触发
// autoUpdater.on('update-not-available', (info) => {}) // 通知渲染进程,没有检测到新版本
// // 发现可更新版本后-用户操作“立即更新”,此时触发开始下载更新
// autoUpdater.downloadUpdate().then((path)=>{})
// // 下载监听-下载进度数据(0-100%)
// autoUpdater.on('download-progress', (progressObj) => {}) //通知渲染进程,下载进度条界面UI展示
// // 更新包下载完成时触发
// autoUpdater.on('update-downloaded', () => {}) // 用于通知渲染进程下载完成-弹层询问是否立刻重启并安装
// 执行 重启应用程序并下载后安装更新(只能在update-downloaded发出后调用)
// autoUpdater.quitAndInstall()
ipcMain.on('check-update', (event) => {
  // checkForUpdates();
  update(event.sender);
@@ -185,7 +213,7 @@
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (isDevelopment) { false;
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {