admin管理员组

文章数量:1122846

Tray Icon Not Appearing in Electron App Despite Following Best Practices Body:

I’m working on an Electron app and trying to display a tray icon in the system tray/notification area. However, the tray icon does not appear at all, even after following all the recommended steps to implement and retain the Tray object.

I’ve tried multiple approaches and ensured the implementation follows Electron’s documentation, but nothing seems to work. Here are the steps I’ve performed: My Setup:

• Electron Version: 32.1.2

• OS: Window 11 or Windows server

• Packaging Tool: Electron Forge

What I’ve Tried:

  1. Global Reference for Tray Object

I declared the Tray object as a global variable to prevent it from being garbage-collected. Here’s my code:

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

let tray = null; // Global variable

let mainWindow;

app.whenReady().then(() => {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
        },
    });

    mainWindow.loadFile('index.html');

    // Create the tray icon
    const iconPath = path.join(__dirname, 'icon.png'); // Path to the tray icon
    tray = new Tray(iconPath); // Create tray icon
    tray.setToolTip('My Electron App'); // Set tooltip

    const contextMenu = Menu.buildFromTemplate([
        { label: 'Show App', click: () => mainWindow.show() },
        { label: 'Quit', click: () => app.quit() },
    ]);

    tray.setContextMenu(contextMenu); // Attach menu to tray

    tray.on('click', () => {
        if (mainWindow.isVisible()) {
            mainWindow.hide();
        } else {
            mainWindow.show();
        }
    });
});

app.on('window-all-closed', (event) => {
    event.preventDefault(); // Keep the app running
});

app.on('before-quit', () => {
    tray.destroy(); // Cleanup tray
});

本文标签: Tray icon not appearing after installing Electron Forge appStack Overflow