首页 > 解决方案 > 如何在任务中使用命令行参数退出应用程序

问题描述

我正在使用电子 5.0.0,我正在尝试使用 windows JumpList 和任务类别来退出我的电子应用程序。

    {
        program: process.execPath,
        arguments: '--new-window',
        iconPath: process.execPath,
        iconIndex: 0,
        title: 'New Window',
        description: 'Create a new window'
    }
])

我正在尝试修改电子网站上的示例代码,我需要更改参数

“arguments String - 程序执行时的命令行参数。”

我知道 windows 已经内置了 --new-window 之类的参数

所以我的问题是windows是否有一些会退出应用程序的东西,或者我需要做一个自定义参数,如果是这样,我将如何去做

我希望它具有与 Skype 相同的功能参见图片 在此处输入图像描述

编辑:

我尝试使用第二个实例事件,但是当用户单击任务时似乎没有调用它

app.setUserTasks([
    {
        program: process.execPath,
        arguments: '--force-quit',
        iconPath: process.execPath,
        iconIndex: 0,
        title: 'Force Quit App',
        description: 'This will close the app instead of minimizing it.'
    }
])
app.on('second-instance', (e, argv)=>{
    console.log("secinst" + argv)
    if(argv === '--force-quit'){
        win.destroy();
    }

})

标签: javascriptelectron

解决方案


如果你设置这样的任务:

app.setUserTasks([
    {
        program: process.execPath,
        arguments: '--force-quit',
        iconPath: process.execPath,
        iconIndex: 0,
        title: 'Force Quit App',
        description: 'This will close the app instead of minimizing it.'
    }
])

单击时,这将使用命令行参数启动应用程序的新实例--force-quit。你应该处理那个论点。

仅当您允许运行应用程序的单个实例时,您的用例才有意义。你需要argvsecond-instance事件中获得。

const { app } = require('electron')
let myWindow = null

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, argv, workingDirectory) => {
    // Someone tried to run a second instance
    const forceQuit = argv.indexOf("--force-quit") > -1;
    if (forceQuit) app.quit()
  })

  // Create myWindow, load the rest of the app, etc...
  app.on('ready', () => {
  })
}

推荐阅读