跳到內容
Tauri

系統 Tray

Tauri 允許您為應用程式建立和自訂系統 tray。這可以通過提供對常用操作的快速訪問來增強使用者體驗。

組態

首先,更新您的 Cargo.toml 以包含系統 tray 的必要功能。

src-tauri/Cargo.toml
tauri = { version = "2.0.0", features = [ "tray-icon" ] }

用法

Tray API 在 JavaScript 和 Rust 中均可用。

建立 Tray 圖示

使用 TrayIcon.new 靜態函數來建立新的 tray 圖示

import { TrayIcon } from '@tauri-apps/api/tray';
const options = {
// here you can add a tray menu, title, tooltip, event handler, etc
};
const tray = await TrayIcon.new(options);

請參閱 TrayIconOptions 以獲取有關自訂選項的更多資訊。

變更 Tray 圖示

在建立 tray 時,您可以使用應用程式圖示作為 tray 圖示

import { TrayIcon } from '@tauri-apps/api/tray';
import { defaultWindowIcon } from '@tauri-apps/api/app';
const options = {
icon: await defaultWindowIcon(),
};
const tray = await TrayIcon.new(options);

新增選單

要附加在點擊 tray 時顯示的選單,您可以使用 menu 選項。

import { TrayIcon } from '@tauri-apps/api/tray';
import { Menu } from '@tauri-apps/api/menu';
const menu = await Menu.new({
items: [
{
id: 'quit',
text: 'Quit',
},
],
});
const options = {
menu,
menuOnLeftClick: true,
};
const tray = await TrayIcon.new(options);

監聽選單事件

在 JavaScript 中,您可以直接將選單點擊事件監聽器附加到選單項目

  • 使用共享選單點擊處理器

    import { Menu } from '@tauri-apps/api/menu';
    function onTrayMenuClick(itemId) {
    // itemId === 'quit'
    }
    const menu = await Menu.new({
    items: [
    {
    id: 'quit',
    text: 'Quit',
    action: onTrayMenuClick,
    },
    ],
    });
  • 使用專用的選單點擊處理器

    import { Menu } from '@tauri-apps/api/menu';
    const menu = await Menu.new({
    items: [
    {
    id: 'quit',
    text: 'Quit',
    action: () => {
    console.log('quit pressed');
    },
    },
    ],
    });

監聽 Tray 事件

tray 圖示會針對以下滑鼠事件發出事件

  • click:當游標收到單次左鍵、右鍵或中鍵點擊時觸發,包括有關滑鼠按鈕是否已釋放的資訊
  • Double click:當游標收到雙擊左鍵、右鍵或中鍵點擊時觸發
  • Enter:當游標進入 tray 圖示區域時觸發
  • Move:當游標在 tray 圖示區域周圍移動時觸發
  • Leave:當游標離開 tray 圖示區域時觸發
import { TrayIcon } from '@tauri-apps/api/tray';
const options = {
action: (event) => {
switch (event.type) {
case 'Click':
console.log(
`mouse ${event.button} button pressed, state: ${event.buttonState}`
);
break;
case 'DoubleClick':
console.log(`mouse ${event.button} button pressed`);
break;
case 'Enter':
console.log(
`mouse hovered tray at ${event.rect.position.x}, ${event.rect.position.y}`
);
break;
case 'Move':
console.log(
`mouse moved on tray at ${event.rect.position.x}, ${event.rect.position.y}`
);
break;
case 'Leave':
console.log(
`mouse left tray at ${event.rect.position.x}, ${event.rect.position.y}`
);
break;
}
},
};
const tray = await TrayIcon.new(options);

請參閱 TrayIconEvent 以獲取有關事件有效負載的更多資訊。


© 2025 Tauri 貢獻者。CC-BY / MIT