systray

package module
v0.0.0-...-5c1775c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 17, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

systray

本仓库是 getlantern/systray 的延续分支(上游自 v1.2.0 之后基本停更)。 模块路径为 github.com/Drelf2018/systray,最低 Go 版本 1.27。

相对上游的改动

图标
  • 新增 ToICON(data []byte) ([]byte, error):把任意图片字节转成当前平台能直接加载的图标格式,结果可以直接交给 SetIcon。 已经是后端原生格式的(Windows 的 .ico,其余平台的 .png/.jpeg/.ico)交回的就是原样的字节——不重新编码、不缩放;其余格式(PNG、JPEG、GIF、BMP、TIFF、WebP、SVG)解码后重新编码。认不出来的数据报错返回,不会交出一个残缺图标。
  • SVG 由 github.com/Drelf2018/oksvg 的 svg 包处理:image.Decode 交回一个尚未光栅化的 *svg.Image,再按平台要求的尺寸 Resize(Windows 上即 SM_CXSMICON),因此不经过中间位图,也不做二次缩放。
  • Windows 不再落地临时文件:.ico 从内存中的资源位图直接构建(CreateIconFromResourceEx),并按 SM_CXSMICON 挑选最合适的一档。
  • 菜单项图标带真正的 alpha 通道(32 位自顶向下 DIB、预乘 alpha),不会再有黑底或悬停时才消失的彩边;替换图标时会释放上一张位图。
API
  • 新增 EnableDPIAwareness() error(仅 Windows,其余平台为空实现):由宿主决定是否声明 DPI 感知。 systray 自己不会调用它——声明感知会让 Windows 停止拉伸本进程的窗口、改发物理像素,手写像素布局的界面可能因此错位。它必须在第一个窗口出现之前调用;Windows 若发现进程已有自己的模式(清单、UI 框架或更早的一次调用)会拒绝,这种拒绝按成功上报,因为进程无论如何已经是感知的。
  • 新增 Logger *slog.Logger:日志改用标准库 log/slog,不再依赖 golog。不设置时写 slog.Default()。
  • 新增 SetOnLeftClick(callback func())(仅 Windows):区分左右键点击;未设置回调时,左键点击回退为弹出菜单。
  • SetIcon 收到空字节切片不再 panic:记一条日志,并保持当前的图标不变。
其他
  • 模块路径改为 github.com/Drelf2018/systray,最低 Go 版本 1.27。
  • Windows 后端是纯 Go,可以 CGO_ENABLED=0 构建;macOS 与 Linux 仍然需要 cgo。
  • 移除仓库内的示例程序;日志去掉了 golog 依赖;另有若干小修(hideMenuItem 吞掉错误、Linux 菜单项结构体泄漏等)。

从上游迁移

把 import 路径从 github.com/getlantern/systray 换成 github.com/Drelf2018/systray 即可,初始化与菜单用法不变。 新增的 ToICON、EnableDPIAwareness、Logger 都是可选项,不调用也照常工作。

用法

package main

import (
	_ "embed"
	"log"

	"github.com/Drelf2018/systray"
)

//go:embed icon.svg
var iconData []byte

func main() {
	// 仅 Windows,且必须在任何窗口出现之前调用。
	if err := systray.EnableDPIAwareness(); err != nil {
		log.Println(err)
	}

	// 任意图片格式进,平台要的图标格式出。
	icon, err := systray.ToICON(iconData)
	if err != nil {
		log.Fatal(err)
	}

	systray.Run(func() {
		systray.SetIcon(icon)
		systray.SetTitle("Awesome App")
		systray.SetTooltip("Pretty awesome 超级棒")

		mQuit := systray.AddMenuItem("Quit", "Quit the whole app")
		go func() {
			<-mQuit.ClickedCh
			systray.Quit()
		}()
	}, func() {
		// 退出前清理
	})
}

菜单项可以勾选、禁用、隐藏,也可以带图标:

mCheck := systray.AddMenuItemCheckbox("Enabled", "Toggle it", true)
mCheck.Check()
mCheck.Disable()
mCheck.SetIcon(icon) // 仅 Windows 与 macOS
mCheck.Hide()

systray is a cross-platform Go library to place an icon and menu in the notification area.

Features

  • Supported on Windows, macOS, and Linux
  • Menu items can be checked and/or disabled
  • Icons may be given as PNG, JPEG, GIF, BMP, TIFF, WebP, ICO or SVG bytes, converted with ToICON
  • Most functions may be called from any goroutine

API

See the full API reference as well as the CHANGELOG.

The package needs cgo on macOS and Linux, so make sure CGO_ENABLED=1 there. On Windows the back-end is pure Go and builds with CGO_ENABLED=0.

Platform notes

Linux
  • Building apps requires gcc as well as the gtk3 and libayatana-appindicator3 development headers to be installed. For Debian or Ubuntu, you may install these using:
sudo apt-get install gcc libgtk-3-dev libayatana-appindicator3-dev

On Linux Mint, libxapp-dev is also required.

If you need to support the older libappindicator3 library instead, you can pass the build flag legacy_appindicator when building. For example:

go build -tags=legacy_appindicator
Windows
  • To avoid opening a console at application startup, use these compile flags:
go build -ldflags -H=windowsgui
  • Call systray.EnableDPIAwareness() before creating any window if you want the tray icon rasterized at the size the display actually draws it at, and if your interface is ready to lay itself out in physical pixels.
macOS

On macOS, you will need to create an application bundle to wrap the binary; simply folders with the following minimal structure and assets:

SystrayApp.app/
  Contents/
    Info.plist
    MacOS/
      go-executable
    Resources/
      SystrayApp.icns

When running as an app bundle, you may want to add one or both of the following to your Info.plist:

<!-- avoid having a blurry icon and text -->
	<key>NSHighResolutionCapable</key>
	<string>True</string>

	<!-- avoid showing the app on the Dock -->
	<key>LSUIElement</key>
	<string>1</string>

Consult the Official Apple Documentation here.

On macOS, it's possible to set the underlying NSStatusItemBehavior with systray.SetRemovalAllowed(true). When enabled, the user can cmd-drag the icon off the menu bar.

Credits

Documentation

Overview

Package systray is a cross-platform Go library to place an icon and menu in the notification area.

Index

Constants

This section is empty.

Variables

View Source
var Logger *slog.Logger

Logger is the logger systray writes to. It is optional: if nil, slog.Default() is used.

Set it before Run. Changing it while the tray is running is not safe.

Functions

func AddSeparator

func AddSeparator()

AddSeparator adds a separator bar to the menu

func EnableDPIAwareness

func EnableDPIAwareness() error

EnableDPIAwareness is a no-op outside Windows: scaled displays are the platform's own business there, and systray reads no desktop metric.

func Quit

func Quit()

Quit the systray. This can be called from any goroutine.

func Register

func Register(onReady func(), onExit func())

Register initializes GUI and registers the callbacks but relies on the caller to run the event loop somewhere else. It's useful if the program needs to show other UI elements, for example, webview. To overcome some OS weirdness, On macOS versions before Catalina, calling this does exactly the same as Run().

func Run

func Run(onReady func(), onExit func())

Run initializes GUI and starts the event loop, then invokes the onReady callback. It blocks until systray.Quit() is called. It must be run from the main thread on macOS.

func SetIcon

func SetIcon(iconBytes []byte)

SetIcon sets the systray icon. iconBytes should be the content of .ico for windows and .ico/.jpg/.png for other platforms. An empty icon is ignored.

func SetOnLeftClick

func SetOnLeftClick(callback func())

SetOnLeftClick sets a callback to be invoked when the tray icon is left-clicked. This is only supported on Windows; on macOS and Linux it does nothing.

func SetRemovalAllowed

func SetRemovalAllowed(allowed bool)

SetRemovalAllowed sets whether a user can remove the systray icon or not. This is only supported on macOS.

func SetTemplateIcon

func SetTemplateIcon(templateIconBytes []byte, regularIconBytes []byte)

SetTemplateIcon sets the systray icon as a template icon (on macOS), falling back to a regular icon on other platforms. templateIconBytes and iconBytes should be the content of .ico for windows and .ico/.jpg/.png for other platforms.

func SetTitle

func SetTitle(title string)

SetTitle sets the systray title, only available on Mac and Linux.

func SetTooltip

func SetTooltip(tooltip string)

SetTooltip sets the systray tooltip to display on mouse hover of the tray icon, only available on Mac and Windows.

func ToICON

func ToICON(data []byte) ([]byte, error)

ToICON converts icon data into the form the platform back-end can load, so the result can be handed straight to SetIcon.

Data already in a format the back-end reads natively — .ico on Windows, and .png, .jpeg or .ico elsewhere — comes back as it went in: those bytes are never re-encoded or resized. The data is decoded first, because the decoder is what names the format, but it is the original bytes that are returned. Anything else is decoded and re-encoded; isNativeIconFormat and encodeIcon spell out the per-platform rules.

Input that is not a recognizable image is reported as an error rather than as a partial icon.

Types

type MenuItem struct {
	// ClickedCh is the channel which will be notified when the menu item is clicked
	ClickedCh chan struct{}
	// contains filtered or unexported fields
}

MenuItem is used to keep track each menu item of systray. Don't create it directly, use the one systray.AddMenuItem() returned

func AddMenuItem

func AddMenuItem(title string, tooltip string) *MenuItem

AddMenuItem adds a menu item with the designated title and tooltip. It can be safely invoked from different goroutines. Created menu items are checkable on Windows and OSX by default. For Linux you have to use AddMenuItemCheckbox

func AddMenuItemCheckbox

func AddMenuItemCheckbox(title string, tooltip string, checked bool) *MenuItem

AddMenuItemCheckbox adds a menu item with the designated title and tooltip and a checkbox for Linux. It can be safely invoked from different goroutines. On Windows and OSX this is the same as calling AddMenuItem

func (item *MenuItem) AddSubMenuItem(title string, tooltip string) *MenuItem

AddSubMenuItem adds a nested sub-menu item with the designated title and tooltip. It can be safely invoked from different goroutines. Created menu items are checkable on Windows and OSX by default. For Linux you have to use AddSubMenuItemCheckbox

func (item *MenuItem) AddSubMenuItemCheckbox(title string, tooltip string, checked bool) *MenuItem

AddSubMenuItemCheckbox adds a nested sub-menu item with the designated title and tooltip and a checkbox for Linux. It can be safely invoked from different goroutines. On Windows and OSX this is the same as calling AddSubMenuItem

func (item *MenuItem) Check()

Check a menu item regardless if it's previously checked or not

func (item *MenuItem) Checked() bool

Checked returns if the menu item has a check mark

func (item *MenuItem) Disable()

Disable a menu item regardless if it's previously disabled or not

func (item *MenuItem) Disabled() bool

Disabled checks if the menu item is disabled

func (item *MenuItem) Enable()

Enable a menu item regardless if it's previously enabled or not

func (item *MenuItem) Hide()

Hide hides a menu item

func (item *MenuItem) SetIcon(iconBytes []byte)

SetIcon sets the icon of a menu item. Only works on macOS and Windows. iconBytes should be the content of .ico/.jpg/.png

func (item *MenuItem) SetTemplateIcon(templateIconBytes []byte, regularIconBytes []byte)

SetTemplateIcon sets the icon of a menu item as a template icon (on macOS). On Windows, it falls back to the regular icon bytes and on Linux it does nothing. templateIconBytes and regularIconBytes should be the content of .ico for windows and .ico/.jpg/.png for other platforms.

func (item *MenuItem) SetTitle(title string)

SetTitle set the text to display on a menu item

func (item *MenuItem) SetTooltip(tooltip string)

SetTooltip set the tooltip to show when mouse hover

func (item *MenuItem) Show()

Show shows a previously hidden menu item

func (item *MenuItem) String() string
func (item *MenuItem) Uncheck()

Uncheck a menu item regardless if it's previously unchecked or not

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL