How to open a new window from tray icon of electron

Viewed 600

How to open a new window from tray icon of electron

Currently I am trying to create a window widget. I faced 3 problems.

  1. It was successful until creating a checkbox in the Tray icon right-click menu. But I want to show a new window when the checkbox is clicked. (Because I want to make a settings menu)

I tried to open a new window on the Tray icon, but it was difficult to understand because there was a lot of outdated information using 'remote'. (Remote is currently deprecated. https://www.electronjs.org/docs/api/remote)

  1. For the second question, I made 'always on top' in the right-click menu of the tray icon, but it doesn't work.

  2. I want to add the process of remembering the window position when the app is closed and restoring the coordinates when starting the app, but an error occurs.


const {app, BrowserWindow, Menu, Tray} = require('electron')
const path = require('path')
const url = require('url')


// Multiple execution prevention
const doubleboot = app.requestSingleInstanceLock();
if(!doubleboot){
  app.quit();
}

let win

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    transparent:true,
    frame:false,
    resizable:false,
    webPreferences: {
      nodeIntegration: true,
    },
    alwaysOnTop : false,
    })

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

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

  // Restore window position
  if (localStorage.getItem("windowPosition")) {
    var pos = JSON.parse(localStorage.getItem("windowPosition"));
    win.setPosition(pos[0], pos[1]);
}

  // Emitted when the window is closed.
  win.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.
    // win = null

    // Save window position when closed
    localStorage.setItem("windowPosition", JSON.stringify(win.getPosition()));
  })
}

// https://www.electronjs.org/docs/api/tray

app.whenReady().then(() => {
  tray = new Tray('./img/icon.ico')
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Always on top', type: 'checkbox'},
    { label: "Focus", click: function () { win.focus(); } },
    { label: 'Settings', click: function () { window.open()} },
    { label: "Exit", click: function () { win.close(); } }
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)
  contextMenu.items[0].checked = false


//always on top 
  function checked(){
    if (contextMenu.items[0] === 0 ){
      win.alwaysOnTop = true;
    }
    else {
      win.alwaysOnTop = false;
    }
}

})

app.on('ready', createWindow) 


// app.on('window-all-closed', () => {
//   if (process.platform !== 'darwin') {
//     app.quit()
//   }
// })

// app.on('activate', () => {
//   if (win === null) {
//     createWindow()
//   }
// })
1 Answers

For the second, you can get window state using window.getBounds() and store it to userData

const saveWindowState = (file: any, window: Electron.BrowserWindow) => {
      const windowState = window.getBounds();
      try {
        fs.writeFileSync(file, JSON.stringify(windowState));
      } catch (e) {
        log.error(e);
      }
    }

And then save the state when closing the window

mainWindow.on("blur", () => {
        saveWindowState(boundsInfoPath, mainWindow);
      });

And retrieve info from userData when lauching

const boundsInfoPath = path.join(app.getPath("userData"), "bounds-info.json");
let windowOptions: Electron.BrowserWindowConstructorOptions;
try {
  windowOptions = JSON.parse(fs.readFileSync(boundsInfoPath, "utf-8"));
  if (!windowOptions) {
    throw new Error(
      "Provided bounds info file does not validate, using defaults instead."
    );
  }
} catch (e) {
 
  
}

And apply windowOptions property to the mainWindow

Related