In my application I have a Form that for one of the top level menu items the sub menu items are dynamically created. So the goal is I have always have a top level menu item called "Actions" but the sub items are dynamically generated. The problem I'm having is that for every sub item I add the entire MainMenu repaints and flickers. The problem is more noticeable the more sub menu items that are added due to more paint calls I'm guessing, for instance if I'm only adding one sub menu item it doesn't flicker often but if I'm adding 15 (which is typical for my application) it's noticeable pretty much everytime. Note that this is using MenuItems rather than MenuStrip, we have custom controls developed to support MenuItems and haven't yet transitioned to use MenuStrip.
I created a simple example to demonstrate this where I have one button click that adds 15 sub items to each top level menu item (I have two in my demo "File" and "Edit") and you'll see it calls "DrawMenuBar" 30 times. Here's what the code is doing on a button click:
private void CreateSubMenus()
{
foreach (MenuItem menu in this.Menu.MenuItems)
{
for (int i = 1; i <= 15; i++)
{
MenuItem newSubMenu = new MenuItem();
newSubMenu.Text = "TestSub" + i;
menu.MenuItems.Add(newSubMenu);
}
}
}
Can't embed images as a new user but here's a link to what profiling shows Profiling Adding Sub Menus
So DrawMenuBar is called 30 times.
I've tried using something like:
this.Menu.MenuItems[0].AddRange(
but this ends up causing the same amount of draw calls. The best I could come up with is removing the top level menu item from the MainMenu then making the changes needed, then relinking it, but this also doesn't look that great because the menu item disappears than reappears. Ideally there would be no flickering or any change to the visibility of the top level menu bar as I'm not changing anything there but rather the sub menu items.
Basically, looking if there's an equivalent way to do a Suspend/Resume Layout but for the MainMenu object.