electron主进程基础功能代码集合

"electron": "^11.0.0" 相对于32位win7 兼容性更好一些

const { app, BrowserWindow, remote, ipcMain, screen, dialog, shell } = require('electron');
const asar = require('asar');
const path = require('path');
const fs = require('fs');
const AdmZip = require('adm-zip');
const http = require('http');
const os = require('os');
const { exec } = require('child_process');

const rootPath = path.dirname(app.getPath('exe'));

const production = 'pro';
const winControl = 'pro'; // 是否显示主窗口控制台   dev:显示   pro 不显示

const mainData = {
  production,
  winControl,
  rootPath,
  isMaximized: false,
  exePath: null,
  localAppDataPath: path.join(os.homedir(), 'AppData', 'Local'), //获取local文件夹路径
  desktopDir: path.join(os.homedir(), 'Desktop'), //获取桌面文件夹路径
  processName: 'r',
};

//创建主窗口
function createMinWindow(w = 540, h = 260) {
  win = new BrowserWindow({
    width: w, //宽度
    height: h, //高度
    center: true, //居中
    frame: false, //无边框
    transparent: true, //透明
    backgroundColor: '#00000000',
    resizable: false,
    show: false,
    webPreferences: {
      // preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, //禁用同源策略
    },
  });

  // 打开开发者工具 控制台
  if (mainData.winControl === 'dev') {
    win.webContents.openDevTools();
  }

  if (mainData.production === 'dev') {
    txtConsole.log('本地测试已开启!!!');

    win.loadURL('http://localhost:8081');
  } else {
    txtConsole.log('当前为线上环境!!!');

    win.loadFile('./dist/index.html');
  }

  win.show();

  // 将窗口设置为一直在最上层
  // win.setAlwaysOnTop(true, 'screen-saver');

  //electron 监听窗口尺寸变化
  win.on('resize', (_) => {
    mainData.isMaximized = win.isMaximized();
  });
  
  //electron 监听窗口关闭,清除窗口对象
  win.on('closed', function () {
    win = null;
    tray = null;
  });

  // 监听 resize 消息
  ipcMain.on('resize', (event, w, h) => {
    win.setResizable(true);

    // 调整窗口尺寸
    win.setSize(w, h);

    txtConsole.log('调整窗口尺寸', w, h);

    const { width, height } = screen.getPrimaryDisplay().workAreaSize;
    const x = Math.floor((width - win.getSize()[0]) / 2);
    const y = Math.floor((height - win.getSize()[1]) / 2);

    win.setPosition(x, y);

    win.setResizable(false);

    !event?.sender?.isDestroyed() && event?.sender?.send('resize-msg', true);
  });


  //窗口 最小化
  ipcMain.on('window-min', function () {
    // 收到渲染进程的窗口最小化操作的通知,并调用窗口最小化函数,执行该操作
    win.minimize();
  });

  //窗口 最大化、恢复
  ipcMain.on('window-max', function (event, w = 1280, h = 800) {
    win.setResizable(true);

    // 为true表示窗口已最大化
    if (mainData.isMaximized) {
      win.setSize(w, h);

      const { width, height } = screen.getPrimaryDisplay().workAreaSize;
      const x = Math.floor((width - win.getSize()[0]) / 2);
      const y = Math.floor((height - win.getSize()[1]) / 2);

      win.setPosition(x, y);

      !event?.sender?.isDestroyed() && event?.sender?.send('window-max-msg', 'min');
    } else {
      win.maximize();

      !event?.sender?.isDestroyed() && event?.sender?.send('window-max-msg', 'max');
    }

    win.setResizable(false);
  });

  //关闭窗口
  ipcMain.on('window-close', function () {
    // win?.hide();
    win?.close();
    process.exit();
  });

  //窗口 聚焦
  ipcMain.on('window-focus', function () {
    win?.restore();
    win?.focus();
  });

  //打开文件对应路径
  ipcMain.on('window-open-file-dir', function (event,  filePath) {
    if (!filePath) {
      txtConsole.log('文件路径不正确', filePath);
      return;
    }

    if (!fs.existsSync(path.dirname(filePath))) {
      !event?.sender?.isDestroyed() &&
        event?.sender?.send('window-open-file-dir-msg', {
          msgType: 'err',
          msg: '未找到文件夹,请检测文件夹是否存在',
        });

      return;
    }

    exec(`cmd /c start "" "${path.dirname(filePath)}"`, (err) => {
      if (err) {
        txtConsole.log('打开文件夹失败: ', String(err));

        !event?.sender?.isDestroyed() &&
          event?.sender?.send('window-open-file-dir-msg', {
            msgType: 'err',
            msg: '打开文件夹失败,请手动打开:' + filePath,
          });
      }
    });
  });


  //打开选择目录弹窗
  ipcMain.on('window-open-select-dir', function (event, defaultPath) {
    txtConsole.log('选择目录:', defaultPath);

    dialog
      .showOpenDialog({
        properties: ['openDirectory'],
        defaultPath: defaultPath || '',
      })
      .then(async (result) => {
        if (result.canceled) {
          txtConsole.log('取消选择的安装路径');
          return;
        }

        let downPath = result.filePaths[0];

        txtConsole.log('选择的路径:', downPath);

        !event?.sender?.isDestroyed() &&
          event?.sender?.send(`window-open-select-dir-msg`, {
            msgType: 'success',
            downPath,
          });
      })
      .catch((err) => {
        txtConsole.log(err);

        !event?.sender?.isDestroyed() &&
          event?.sender?.send(`window-open-select-dir-msg`, {
            msgType: 'err',
            msg: err,
          });
      });
  });

 
  // 跳转外链
  ipcMain.on('window-jump-link', function (event, url) {
    if (!url) {
      txtConsole.log('链接无效');
      !event?.sender?.isDestroyed() &&
        event?.sender?.send(`window-jump-link-msg`, {
          msgType: 'err',
          msg: '链接无效',
        });

      return;
    }

    //打开默认浏览器跳转外链
    shell.openExternal(url);
  });

  // 渲染进程 log
  ipcMain.on('electron-msg', function (_, data) {
    txtConsole.log('来自渲染进程的消息:', data);
  });

  //获取用户进程列表
  ipcMain.on('ws-get-tasklist', function (event) {
    exec('chcp 65001 | tasklist', (err, stdout) => {
      if (err) {
        !event?.sender?.isDestroyed() &&
          event?.sender?.send(`ws-get-tasklist-msg`, String(err));

        txtConsole.log(`ws-get-tasklist-exec error: ${err}`);

        return;
      }

      !event?.sender?.isDestroyed() &&
        event?.sender?.send(`ws-get-tasklist-msg`, String(stdout));
    });
  });

  //杀指定进程
  ipcMain.on('ws-kill-progress', function () {
    onKillProcess(['r.exe']);
  });
}

//杀死进程
function onKillProcess(processNameList = []) {
  try {
    (processNameList || [])?.forEach((processName) => {
      const output = execSync(`chcp 65001 && cmd.exe /C taskkill /F /IM ${processName}`);

      txtConsole.log(output.toString());
    });
  } catch (error) {
    txtConsole.log(error.toString());
  }
}

//判断进程是否正在运行
function isProcessRunning(processName) {
  let stdout;

  try {
    // 设置 maxBuffer 为 5MB
    stdout = execFileSync('tasklist', [], { encoding: 'utf8', maxBuffer: 1024 * 5000 });
  } catch (err) {
    txtConsole.log('tasklist isProcessRunning执行失败 执行 return true', err?.message);

    return true;
  }

  return stdout?.toString()?.toLowerCase()?.indexOf(processName.toLowerCase()) > -1;
}

你可能感兴趣的:(electron,javascript,node.js,前端)