IT/Electron

[Electron] 일렉트론 프로그램 닫기 클릭시 트레이로 숨기기 main.js

월공 2021. 3. 24. 09:53
728x90
300x250

 

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

//소스 수정시 자동 새로고침
//require('electron-reload')(__dirname, { electron : require(`${__dirname}/node_modules/electron`) })

function createWindow () {
  const mainWindow = new BrowserWindow({
    width: 500,
    height: 500,
    resizable: false,
    webPreferences: {      
      preload: path.join(__dirname, 'preload.js')
    }
  })

  mainWindow.once("ready-to-show", () => mainWindow.show());
  mainWindow.on("closed", () => (mainWindow = null));

  const iconPath = `${__dirname}/img/트레이아이콘.png`;
  tray = new Tray(nativeImage.createFromPath(iconPath));

  tray.setToolTip("프로그램");
  const contextMenu = Menu.buildFromTemplate([
    {
      label: "열기",
      type: "normal",
      click() {
        mainWindow.show();
      }
    },
    { label: "닫기", type: "normal", role: "quit" }
  ]);
  tray.on("click", () => (mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()));
  tray.setContextMenu(contextMenu);
  mainWindow.on("close", e => {
    if (mainWindow.isVisible()) {
      mainWindow.hide();
      e.preventDefault();
    }
  });
  //개발자 도구
  //mainWindow.webContents.openDevTools()
  mainWindow.loadFile('index.html')
}

//프로그램 메뉴 안보이기
Menu.setApplicationMenu(false)

app.whenReady().then(() => {
  createWindow()
  
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

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

 

728x90
300x250