如何在不打开窗口的情况下打开电子应用程序

时间:2019-04-23 02:23:52

标签: javascript electron

im在Electron中制作剪贴板应用程序。到目前为止,我已经做好了准备,因此您可以打开该程序,它将进入托盘,但同时也会打开一个窗口,并且我的程序无法正常运行。 这是我的代码。我一直在摸索,试图弄清楚如何在不打开窗口的情况下运行该程序。

TIA

代码:

// Modules to control application life and create native browser window
const {app, BrowserWindow, globalShortcut, Tray, Menu} = require('electron')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow



function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true

    }
  })

  const ret = globalShortcut.register("Super+Alt+V", () => {
     mainWindow.isVisible()
      ? mainWindow.hide()
      : mainWindow.show();
    });


    if(!ret) {
      console.error('failed to register hotkey');
    }


    tray = new Tray('./Nstar2.jpg');
    tray.setToolTip('Racesim');

    tray.displayBalloon({
      title: "Hey",
      content: "It looks like you copied something..."
    });

    const contextMenu = Menu.buildFromTemplate([
    {label: 'Exit', type: 'normal', click:() => {
      app.quit();
    }},

    ])

    tray.setContextMenu(contextMenu);

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// 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.on('ready', createWindow)

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



app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

基本上我希望它能打开并留在托盘中,仅此而已。

1 个答案:

答案 0 :(得分:0)

简而言之,Electron不允许您在不显示窗口的情况下启动应用程序。您唯一的选择是在应用程序启动后立即最小化窗口。

大多数人似乎都依靠auto-launch软件包(或类似软件包)来实现这一目标。该程序包仅允许您将参数传递并解析到节点应用。

这里有一些有用的资源,我建议您检查一下: