0

As per Cody's answer to this question, I derived a class from ContextMenuStrip and handle the ProcessCmdKey. This successfully prevents the menu from closing when pressing Enter while a textbox embedded inside the menu has focus. So all is well except for one thing.

Upon the Enter press, I remove the Textbox from the menu, and disposing this control causes the menu to close. When I do this:

If (m_inputPanel IsNot Nothing) Then m_inputPanel.Hide()
If (m_inputPanel IsNot Nothing) Then m_inputPanel.Parent.Controls.Remove(m_inputPanel)
If (m_inputPanel IsNot Nothing) Then m_inputPanel.Dispose()

the menu is closed. When I comment out the third line, the menu remains open. (Incidentally, m_inputPanel.Parent is a custom control which is embedded inside the menu using a ToolStripControlHost)

Why on God's Green Earth does it matter that I dispose a control which is no longer part of the menu?

Community
  • 1
  • 1
David Rutten
  • 4,716
  • 6
  • 43
  • 72
  • 2
    Check this answer for a better way: http://stackoverflow.com/questions/5207767/net-multiple-toolstripbuttons-in-a-single-contextmenuitem/5207964#5207964 – Hans Passant Mar 06 '11 at 01:12
  • 1
    I just noticed this question, and feel somewhat compelled to reply since I'm the one that gave you the original solution. In this case, I agree with Hans. I tried to suggest in the comments to your previous question that I didn't think using a `ContextMenuStrip` was the best general approach to your problem, but since the immediate solution was so simple, I tried to provide a helpful answer. I'm sorry if you've wasted a bunch of time getting the CMS to work. I don't know a workaround here; I don't use the CMS much myself for multiple reasons, including the fragile behavior Hans discusses. – Cody Gray - on strike Mar 06 '11 at 07:52
  • @Cody, not at all. I'm most grateful for your answer. The Disposing problem might yet be overcome, and even if it isn't, I can always figure out a way to add these controls to some sort of list to be disposed after the menu is closed. – David Rutten Mar 06 '11 at 09:44

1 Answers1

1

You are removing focus from the context menu when you do this, since it was the textbox that had focus when you removed it now there is nothing in the ContextMenuStrip that has focus any more.

msarchet
  • 15,104
  • 2
  • 43
  • 66
  • So not disposing the textbox but removing it from the menu as a control *doesn't* remove focus? Hmm, odd. Though it explains what's happening. I'll try and set focus back to the menu prior to disposing, see if that helps. – David Rutten Mar 05 '11 at 22:37
  • @DavidRutten that is an interesting question, I would image that it is some odd caveat of the controls. – msarchet Mar 05 '11 at 23:22
  • It is an excellent theory. Unfortunately that should also close the CMS when the panel is hidden and not disposed. – Hans Passant Mar 05 '11 at 23:36