@@ -163,8 +163,7 @@ var defaultWHWND: HWND = undefined;
163163pub const Window = struct {
164164 hwnd : HWND ,
165165 source_dpi : u32 = 96 ,
166- /// List of menus and submenus
167- menus : std .ArrayList (HMENU ),
166+ root_menu : ? HMENU ,
168167 /// List of menu item callbacks, where the index is the menu item ID
169168 menu_item_callbacks : std .ArrayList (? * const fn () void ),
170169
@@ -256,7 +255,7 @@ pub const Window = struct {
256255 defaultWHWND = hwnd ;
257256 return Window {
258257 .hwnd = hwnd ,
259- .menus = std . ArrayList ( HMENU ). init ( lib . internal . lasting_allocator ) ,
258+ .root_menu = null ,
260259 .menu_item_callbacks = std .ArrayList (? * const fn () void ).init (
261260 lib .internal .lasting_allocator ,
262261 ),
@@ -297,8 +296,6 @@ pub const Window = struct {
297296 item .config .label ,
298297 );
299298 try initMenu (self , submenu , item .items );
300- // Append submenus in reverse order for freeing correctly
301- try self .menus .append (submenu );
302299 } else {
303300 _ = win32 .AppendMenuA (
304301 menu ,
@@ -312,27 +309,27 @@ pub const Window = struct {
312309 }
313310
314311 fn clearAndFreeMenus (self : * Window ) void {
315- for (self .menus .items ) | menu | {
316- var position_index : u32 = 0 ;
317- // Delete all items until failure to delete
318- while (win32 .DeleteMenu (menu , position_index , win32 .MF_BYPOSITION ) != 0 ) {
319- position_index += 1 ;
320- }
321- }
322- self .menus .clearAndFree ();
312+ _ = win32 .DestroyMenu (self .root_menu );
323313 self .menu_item_callbacks .clearAndFree ();
314+ self .root_menu = null ;
324315 }
325316
326317 pub fn setMenuBar (self : * Window , bar : lib.MenuBar ) void {
327- const rootMenu = win32 .CreateMenu ().? ;
318+ // Detach and free current menu (if exists) from window first.
319+ _ = win32 .SetMenu (self .hwnd , null );
328320 self .clearAndFreeMenus ();
329- self .initMenu (rootMenu , bar .menus ) catch {
330- // TODO: Handle error in appropriate way
331- };
332- self .menus .append (rootMenu ) catch {
321+
322+ const root_menu = win32 .CreateMenu ().? ;
323+ self .initMenu (root_menu , bar .menus ) catch {
333324 // TODO: Handle error in appropriate way
334325 };
335- _ = win32 .SetMenu (self .hwnd , rootMenu );
326+ if (win32 .SetMenu (self .hwnd , root_menu ) != 0 ) {
327+ self .root_menu = root_menu ;
328+ } else {
329+ self .menu_item_callbacks .clearAndFree ();
330+ }
331+
332+ // Ensure menu item callbacks can be accessed during event processing.
336333 getEventUserData (self .hwnd ).classUserdata = @intFromPtr (self );
337334 }
338335
0 commit comments