FAQ - Help and questions

How do I add a system tray icon with a menu to a Rust app on Windows and macOS?

#system-tray#tray-icon#winit#desktoppublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

The tray-icon crate creates a tray icon with a menu. It needs an event loop running on the thread that creates the icon, and on macOS the main thread, so create it after the loop starts, for example in resumed. Menu clicks arrive through a handler. The Windows code passed cargo check.

Checked with rustc 1.93.0, Windows 11, tray-icon 0.21.3 with winit 0.30.13; `cargo check` only. No icon was shown and nothing was run on a Mac. Event loop rules are quoted from the tray-icon documentation.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

tray-icon documents these rules:

  • Windows and Linux: "an event loop must be running on the thread", and you "have to create the tray icon on the same thread as the event loop".
  • macOS: "an event loop must be running on the main thread so you also need to create the tray icon on the main thread", and "the event loop [must be] already running and not just created before creating a TrayIcon".

So the icon is built inside the running loop. In winit 0.30 the place is ApplicationHandler::resumed. The menu's clicks are delivered to a handler you set; forwarding them into the loop as user events wakes the loop for each click.

src/main.rsrust
use tray_icon::menu::{Menu, MenuEvent, MenuId, MenuItem};
use tray_icon::{Icon, TrayIcon, TrayIconBuilder};
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId;

enum UserEvent {
    Menu(MenuEvent),
}

#[derive(Default)]
struct App {
    quit_id: Option<MenuId>,
    tray: Option<TrayIcon>, // dropping the TrayIcon removes the icon
}

impl ApplicationHandler<UserEvent> for App {
    // The event loop is running when this is called, which is when the tray icon must be created.
    fn resumed(&mut self, _el: &ActiveEventLoop) {
        if self.tray.is_some() {
            return;
        }
        let menu = Menu::new();
        let quit = MenuItem::new("Quit", true, None);
        menu.append(&quit).unwrap();
        self.quit_id = Some(quit.id().clone());

        // A 16x16 solid orange square as the icon: RGBA, 4 bytes per pixel.
        let rgba: Vec<u8> = (0..16 * 16).flat_map(|_| [0xC2, 0x41, 0x0C, 0xFF]).collect();
        let icon = Icon::from_rgba(rgba, 16, 16).unwrap();
        self.tray = Some(TrayIconBuilder::new().with_menu(Box::new(menu)).with_tooltip("My app").with_icon(icon).build().unwrap());
    }

    fn window_event(&mut self, _el: &ActiveEventLoop, _id: WindowId, _e: WindowEvent) {}

    // Menu clicks are forwarded into the loop (see main), so the loop wakes up for them.
    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
        let UserEvent::Menu(event) = event;
        if Some(&event.id) == self.quit_id.as_ref() {
            event_loop.exit();
        }
    }
}

fn main() {
    let event_loop = EventLoop::<UserEvent>::with_user_event().build().unwrap();
    event_loop.set_control_flow(ControlFlow::Wait);
    let proxy = event_loop.create_proxy();
    MenuEvent::set_event_handler(Some(move |e| {
        let _ = proxy.send_event(UserEvent::Menu(e));
    }));
    event_loop.run_app(&mut App::default()).unwrap();
}

This is the shape of the code that was checked with tray-icon 0.21.3 and winit 0.30.13 on Windows. It was not run, so no tray icon was seen.

Design notes:

  • Keep the TrayIcon value alive. It is stored in the app struct above; dropping it removes the icon.
  • Icon: the sample builds a plain 16 by 16 RGBA square. Use a real image of the size your platform expects; check each platform's guidelines (macOS menu bar icons are usually monochrome "template" images, per Apple's human interface guidelines, which were not checked here).
  • Tray apps without a window: a program that lives only in the tray still needs the event loop. If you also use a toolkit (egui, Slint), read its documentation for how to run the tray in the same loop or in a second thread; the rules above apply to whichever thread owns the loop.
  • Quit entry: always give the tray a way to quit; a program with no window and no menu can only be killed from the task manager.

Common mistakes#

  • Creating the tray icon before the loop runs (in main), which the macOS documentation above forbids.
  • Creating it on a worker thread without an event loop on that thread.
  • Letting the TrayIcon go out of scope at the end of a function.

Does tray-icon work on Linux?#

Its documentation has a section for Linux with extra requirements; this thread covers Windows and macOS only.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet