electron使用nodejs关机重启,调节声音(window/linux)

node v14.17.4

"electron": "^16.0.2"

1.关机重启调节声音

model/system.js

const os = require("os");
const execShell = require("child_process").exec;
const loudness = require("loudness");
let shutdownShell = "shutdown -s -t 00";
let rebootShell = "shutdown -r -t 0";
if (os.platform() != "win32") {
  shutdownShell = "shutdown now";
  rebootShell = "shutdown -r now";
}
// console.log(os.platform());
//关机
exports.shutdownOs = (channel, args) => {
  let command = execShell(shutdownShell, function (err, stdout, stderr) {
    if (err || stderr) {
      console.log("shutdown failed" + err + stderr);
    }
  });
  command.stdin.end();
  command.on("close", function (code) {
    console.log("shutdown", code);
  });
};
//重启
exports.rebootOs = (channel, args) => {
  let command = execShell(rebootShell, function (err, stdout, stderr) {
    if (err || stderr) {
      console.log("reboot failed" + err + stderr);
    }
  });
  command.stdin.end();
  command.on("close", function (code) {
    console.log("reboot", code);
  });
};

// 设置音量为特定值
exports.setSound = async (channel, soundVal) => {
  console.log(soundVal);
  await loudness.setVolume(soundVal);
};
// console.log("sound:", loudness.getVolume());
// 获取当前音量
exports.getSound = async (channel, args) => {
  let val = await loudness.getVolume();
  channel.returnValue = {
    status: true,
    data: val,
  };
};

electron 主文件

main.js

const { app, BrowserWindow, ipcMain, Menu, MenuItem } = require("electron");
const path = require("path");
const NODE_ENV = process.env.NODE_ENV;

let osObj = require("./model/system");
//测试
ipcMain.on("test", (channel, args) => {
  channel.returnValue = args;
});
//中心管理
ipcMain.on("shutdownOs", osObj.shutdownOs);
ipcMain.on("rebootOs", osObj.rebootOs);
ipcMain.on("getSound", osObj.getSound);
ipcMain.on("setSound", osObj.setSound);
function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 980,
    height: 680,
    transparent: true,
    // fullscreen: true,
    frame: false,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });
  const menu = new Menu();
  menu.append(new MenuItem({ label: "复制", role: "copy" }));
  menu.append(new MenuItem({ label: "粘贴", role: "paste" }));
  menu.append(new MenuItem({ label: "刷新", role: "forceReload" }));
  mainWindow.webContents.on("context-menu", (e, params) => {
    menu.popup({ window: mainWindow, x: params.x, y: params.y });
  });

  if (NODE_ENV === "development") {
    mainWindow.loadURL("http://localhost:8080/");
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadURL(`file://${path.join(__dirname, "../dist/index.html")}`);
  }
}

// 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.
app.whenReady().then(() => {
  createWindow();
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

2. 前端代码

"ant-design-vue": "^3.1.0",

"vue": "^3.0.0",

import { defineComponent, reactive, toRefs, onUnmounted, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";

//设置配置
export default defineComponent({
  components: {
    LoginOutlined,
    UserOutlined,
    SettingOutlined,
    SoundOutlined,
    QuestionCircleOutlined,
    MyIcon,
  },
  setup() {
    

    //声音
    let soundValTemp = 0;
    onMounted(() => {
      //获取声音值
      let soundObj = (window as any).ipcRender.sendSync("getSound", {});
      state.soundVal = soundObj.data;
      soundValTemp = cloneDeep(soundObj.data);
      console.log(soundObj);
    });

    const changeSound = () => {
      if (soundValTemp != state.soundVal) {
        (window as any).ipcRender.send("setSound", state.soundVal);
      }
    };
    //关机和重启
    const handleOsCommand = (command: string) => {
      state.actionBtnDisable = true;
      if ("shutdown" === command || "reboot" === command) {
        let warningText = "确定要重启吗?";
        let okBtnText = "确定重启";
        let commandFun = "rebootOs";
        if ("shutdown" === command) {
          warningText = "确定要关机吗?";
          okBtnText = "确定关机";
          commandFun = "shutdownOs";
        }
        Modal.confirm({
          content: warningText,
          width: 230,
          icon: "",
          bodyStyle: {
            fontWeight: "bolder",
            textAlign: "center",
          },
          centered: true,
          onOk() {
            (window as any).ipcRender.send(commandFun, {});
          },
          okText: okBtnText,
          cancelText: "取消",
          onCancel() {
            Modal.destroyAll();
            state.actionBtnDisable = false;
          },
        });
      }
    };
    return {
      changeSound,
      handleOsCommand,
    };
  },
});
posted @ 2022-04-12 09:10  sentangle  阅读(925)  评论(0编辑  收藏  举报