From 35cc7fd569503f720a98f5eb9f68e6ffa43bfae7 Mon Sep 17 00:00:00 2001 From: Ian VanSchooten Date: Thu, 6 Mar 2025 08:49:22 -0500 Subject: [PATCH] Avoid adding duplicate menuitems (windows) Previously, when calling `.SetHidden(false)` on a menu item that was not hidden, a duplicate menu item was created. --- v3/examples/menu/main.go | 2 +- v3/examples/systray-custom/main.go | 11 +++++++++-- v3/pkg/application/menuitem_windows.go | 7 ++++--- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/v3/examples/menu/main.go b/v3/examples/menu/main.go index 1809fce0c..a9ae843b8 100644 --- a/v3/examples/menu/main.go +++ b/v3/examples/menu/main.go @@ -46,7 +46,7 @@ func main() { // Hidden menu item that can be unhidden hidden := myMenu.Add("I was hidden").SetHidden(true) - myMenu.Add("Toggle hidden menu").OnClick(func(ctx *application.Context) { + myMenu.Add("Toggle the hidden menu").OnClick(func(ctx *application.Context) { hidden.SetHidden(!hidden.Hidden()) }) diff --git a/v3/examples/systray-custom/main.go b/v3/examples/systray-custom/main.go index 2aa244ba4..fee979406 100644 --- a/v3/examples/systray-custom/main.go +++ b/v3/examples/systray-custom/main.go @@ -2,11 +2,12 @@ package main import ( _ "embed" + "log" + "runtime" + "github.com/wailsapp/wails/v3/pkg/application" "github.com/wailsapp/wails/v3/pkg/events" "github.com/wailsapp/wails/v3/pkg/icons" - "log" - "runtime" ) var windowShowing bool @@ -52,6 +53,12 @@ func main() { systemTray := app.NewSystemTray() menu := app.NewMenu() + // Hidden menu item that can be unhidden + hidden := menu.Add("I was hidden").SetHidden(true) + menu.Add("Toggle the hidden menu").OnClick(func(ctx *application.Context) { + hidden.SetHidden(!hidden.Hidden()) + menu.Update() + }) menu.Add("Quit").OnClick(func(data *application.Context) { app.Quit() }) diff --git a/v3/pkg/application/menuitem_windows.go b/v3/pkg/application/menuitem_windows.go index 44d825f1b..31cf0f248 100644 --- a/v3/pkg/application/menuitem_windows.go +++ b/v3/pkg/application/menuitem_windows.go @@ -24,8 +24,8 @@ type windowsMenuItem struct { } func (m *windowsMenuItem) setHidden(hidden bool) { - m.hidden = hidden - if m.hidden { + if hidden && !m.hidden { + m.hidden = true // iterate the parent items and find the menu item before us for i, item := range m.parent.items { if item == m.menuItem { @@ -41,7 +41,8 @@ func (m *windowsMenuItem) setHidden(hidden bool) { // m.pos = w32.GetMenuItemPosition(m.hMenu, uint32(m.id)) // Remove from parent menu w32.RemoveMenu(m.hMenu, m.id, w32.MF_BYCOMMAND) - } else { + } else if !hidden && m.hidden { + m.hidden = false // Add to parent menu // Get the position of the item before us var pos int