golang跨平台系统任务栏图标管理插件库trayhost的使用

golang跨平台系统任务栏图标管理插件库trayhost的使用

trayhost是一个跨平台的Go库,用于在宿主操作系统的任务栏中放置图标。

平台支持

  • macOS - 完全实现并支持
  • Linux - 部分实现,但不受支持(需要维护者)
  • Windows - 部分实现,但不受支持(需要维护者)

注意事项

在macOS上,要使通知中心的用户通知正常工作,使用trayhost的Go二进制文件必须是标准macOS应用程序包的一部分。

trayhost的大多数其他功能在二进制文件不是应用程序包的一部分时也可用,但会出现终端弹出窗口,并且无法配置应用程序的某些方面。

示例代码

下面是一个完整的trayhost使用示例:

package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/shurcooL/trayhost"
)

func main() {
	// 设置菜单项
	menuItems := []trayhost.MenuItem{
		{
			Title: "关于",
			Handler: func() {
				fmt.Println("点击了关于菜单")
			},
		},
		trayhost.SeparatorMenuItem(),
		{
			Title: "退出",
			Handler: func() {
				fmt.Println("点击了退出菜单")
				trayhost.Exit()
			},
		},
	}

	// 初始化trayhost
	err := trayhost.Initialize("我的应用", menuItems)
	if err != nil {
		log.Fatalln("初始化失败:", err)
	}

	// 设置图标(仅macOS需要)
	ep, err := os.Executable()
	if err != nil {
		log.Fatalln("os.Executable:", err)
	}
	err = os.Chdir(filepath.Join(filepath.Dir(ep), "..", "Resources"))
	if err != nil {
		log.Fatalln("os.Chdir:", err)
	}

	// 进入主循环
	trayhost.EnterLoop()
}

macOS应用包结构

要使上述代码在macOS上正常工作,需要将其打包为标准的macOS应用包结构:

Trayhost Example.app
└── Contents
    ├── Info.plist
    ├── MacOS
    │   └── example
    └── Resources
        └── Icon.icns

Info.plist示例

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleExecutable</key>
	<string>example</string>
	<key>CFBundleIconFile</key>
	<string>Icon</string>
	<key>CFBundleIdentifier</key>
	<string>ExampleApp</string>
	<key>NSHighResolutionCapable</key>
	<true/>
	<key>LSUIElement</key>
	<string>1</string>
</dict>
</plist>

安装

使用以下命令安装trayhost库:

go get github.com/shurcooL/trayhost

许可证

MIT License


更多关于golang跨平台系统任务栏图标管理插件库trayhost的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang跨平台系统任务栏图标管理插件库trayhost的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用trayhost管理Go应用的跨平台系统任务栏图标

trayhost是一个Go语言的跨平台系统任务栏图标管理库,支持Windows、macOS和Linux系统。下面我将详细介绍如何使用trayhost为你的Go应用添加系统托盘图标功能。

安装trayhost

首先使用go get安装trayhost:

go get github.com/shurcooL/trayhost

基本使用示例

下面是一个简单的示例,展示如何创建一个带有菜单的系统托盘图标:

package main

import (
	"fmt"
	"github.com/shurcooL/trayhost"
)

func main() {
	// 初始化托盘图标
	trayhost.Initialize("My App", iconData) // iconData是[]byte格式的图标数据

	// 创建菜单项
	menuItems := []trayhost.MenuItem{
		{
			Title: "显示主窗口",
			Handler: func() {
				fmt.Println("显示主窗口被点击")
			},
		},
		trayhost.SeparatorMenuItem(),
		{
			Title: "退出",
			Handler: func() {
				fmt.Println("退出应用")
				trayhost.Exit()
			},
		},
	}

	// 设置菜单
	trayhost.UpdateMenu(menuItems)

	// 设置点击图标时的回调
	trayhost.SetOnClick(func() {
		fmt.Println("托盘图标被点击")
	})

	// 进入事件循环
	trayhost.EnterLoop()
}

图标数据准备

trayhost需要[]byte格式的图标数据。你可以使用以下方式准备图标:

  1. 直接嵌入图标文件:
//go:embed icon.png
var iconData []byte
  1. 或者从文件加载:
func loadIcon(path string) []byte {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatal(err)
	}
	return data
}

高级功能

动态更新菜单

你可以随时更新菜单项:

func updateMenu() {
	newItems := []trayhost.MenuItem{
		{
			Title: "新选项",
			Handler: func() {
				fmt.Println("新选项被点击")
			},
		},
	}
	trayhost.UpdateMenu(newItems)
}

处理通知

trayhost也支持系统通知:

func showNotification() {
	trayhost.Notify("标题", "这是通知内容")
}

平台特定注意事项

  1. Windows:需要.ico格式的图标
  2. macOS:推荐使用.png格式,支持透明背景
  3. Linux:不同桌面环境可能有不同表现

完整示例

下面是一个更完整的示例,展示了一个有状态的应用:

package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/shurcooL/trayhost"
)

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

var isRunning = true

func main() {
	// 初始化托盘
	trayhost.Initialize("状态监控", iconData)

	// 创建菜单
	menuItems := []trayhost.MenuItem{
		{
			Title: "开始/停止",
			Handler: func() {
				isRunning = !isRunning
				updateStatus()
				trayhost.Notify("状态变更", fmt.Sprintf("监控已%v", map[bool]string{true: "开始", false: "停止"}[isRunning]))
			},
		},
		trayhost.SeparatorMenuItem(),
		{
			Title: "退出",
			Handler: func() {
				trayhost.Exit()
				os.Exit(0)
			},
		},
	}

	trayhost.UpdateMenu(menuItems)
	updateStatus()

	// 模拟后台任务
	go func() {
		for {
			if isRunning {
				log.Println("执行监控任务...")
			}
			time.Sleep(5 * time.Second)
		}
	}()

	trayhost.EnterLoop()
}

func updateStatus() {
	menuItems := []trayhost.MenuItem{
		{
			Title: fmt.Sprintf("状态: %s", map[bool]string{true: "运行中", false: "已停止"}[isRunning]),
			Enabled: false,
		},
		trayhost.SeparatorMenuItem(),
		{
			Title: "开始/停止",
			Handler: func() {
				isRunning = !isRunning
				updateStatus()
			},
		},
		trayhost.SeparatorMenuItem(),
		{
			Title: "退出",
			Handler: func() {
				trayhost.Exit()
				os.Exit(0)
			},
		},
	}
	trayhost.UpdateMenu(menuItems)
}

注意事项

  1. 在macOS上,应用必须打包为.app bundle才能正确显示菜单
  2. Linux上可能需要安装额外的依赖,如libappindicator
  3. 调用trayhost.Exit()来清理资源
  4. 主函数最后必须调用trayhost.EnterLoop()来启动事件循环

trayhost提供了一种简单的方式为Go应用添加跨平台的系统托盘支持,适合后台应用或需要最小化到系统托盘的程序。

回到顶部