// pkg/systray/systray.go
packagesystrayimport("context""fyne.io/systray")var(done=make(chanstruct{},1))// Config is the configuration for the systray
typeConfigstruct{TitlestringTooltipstringIconBytes[]byte}// Run the systray and block until systray is closed
funcRun(ctxcontext.Context,cfgConfig){onReady:=func(){systray.SetIcon(cfg.IconBytes)systray.SetTitle(cfg.Title)systray.SetTooltip(cfg.Tooltip)mQuit:=systray.AddMenuItem("Quit","Quit the app")gofunc(){<-mQuit.ClickedChsystray.Quit()}()}onExit:=func(){close(done)}gofunc(){<-ctx.Done()systray.Quit()}()systray.Run(onReady,onExit)}// Done returns a channel that closed when the systray is closed
funcDone()<-chanstruct{}{returndone}
// app.go
packagemainimport("context""fmt"_"embed""github.com/LoveSnowEx/screen-cropper/pkg/systray""github.com/wailsapp/wails/v2/pkg/runtime")//go:embed assets/icon.ico
varicon[]byte// App struct
typeAppstruct{ctxcontext.Context}// NewApp creates a new App application struct
funcNewApp()*App{return&App{}}func(a*App)bindSystray(){// Run the systray
gosystray.Run(a.ctx,systray.Config{Title:"Screen Cropper",Tooltip:"Screen Cropper",IconBytes:icon,})// Quit the app when the systray is closed
gofunc(){<-systray.Done()runtime.Quit(a.ctx)}()}// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func(a*App)startup(ctxcontext.Context){a.ctx=ctxa.bindSystray()}// Greet returns a greeting for the given name
func(a*App)Greet(namestring)string{returnfmt.Sprintf("Hello %s, It's show time!",name)}
以下是修改的部份:
Embed
embed 是 Go 1.16 新增的功能,可以將檔案內嵌到程式碼中,在 build 時會一起編譯。
func(a*App)bindSystray(){// Run the systray
gosystray.Run(a.ctx,systray.Config{Title:"Screen Cropper",Tooltip:"Screen Cropper",IconBytes:icon,})// Quit the app when the systray is closed
gofunc(){<-systray.Done()runtime.Quit(a.ctx)}()}