Context menu persisting beyond its scope

P

Paul E Collins

A context menu is created in the scope of the RightClick event, but it
continues to be displayed after that event handler terminates - i.e.
after it has gone out of scope. The code works correctly, but I feel a
bit odd about it. Is there anything to watch out for here?

By the way, the reason I'm creating the menu dynamically every time is
that the menu's contents and enabled-states can change based on what
the user does, and I don't want to duplicate all of that logic for a
separately maintained context menu.

private void map_RightClick(object sender, EventArgs e)
{
ContextMenu myMenu = new ContextMenu();

MenuItem[] items = (MenuItem[]) new ArrayList(
mnuEdit.MenuItems).ToArray(typeof(MenuItem));

foreach (MenuItem item in items)
myMenu.MenuItems.Add(item.CloneMenu());

myMenu.Show(this, this.PointToClient(Control.MousePosition));
}
 
L

Lucian Wischik

Paul E Collins said:
A context menu is created in the scope of the RightClick event, but it
continues to be displayed after that event handler terminates

No it doesn't! Set a breakpoint at the closing brace. You'll see that
the "Show" command is modal -- i.e. it doesn't return until after the
user has made a selection.

The code works correctly, but I feel a
bit odd about it. Is there anything to watch out for here?

How does Show() accomplish its magic, of being modal while still
allowing the application to pump messages? What will happen if the
user right-clicks to bring up your menu, but then right-clicks again
so invoking your right-click handler and showing a new popup menu even
while the old popup menu is still around?

Fortunately you're saved from this problem. My guess is that they
anticipated this precise case: and they coded it so that, while you're
inside ContextMenu.Show(), it closes itself before proceeding with the
next event.

What if you popped up a context-menu in response to a timer event, and
so the event caused another context-menu to pop up even while the old
context-menu was still visible? This seems not to happen. I don't know
why. We give thanks to the gods of Windows.Forms.


PS. I think it's perfectly good design to create the menu dynamically
each time.
 
M

Michael Sander

PS. I think it's perfectly good design to create the menu dynamically
each time.

The only problem that comes from this design:
You wont be able to use Shortcuts, as the proper MenuItem doesn't exist.
Even worth: You might end up calling some functions wich you belived
disabled.
That's why I prefer to recreate my menuitems on some sort of
DataChange-Event.

Michael Sander
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top