Gabriel
Gabriel

Reputation: 411

How to put control in temporary layer in Windows Forms

I have my own user control created. When I click certain button on my form, I want to display my user control. But I don't want it to be displayed permanently by something like this:

uc.Visible = true;

and then hide it again:

uc.Visible = false;

I want my user control to behave like context menu. When I right-click something, my context menu is shown and then I don't care how to hide my context menu. It is hidden automatically:

How can I achieve this behavior for my user control?

Upvotes: 2

Views: 77

Answers (1)

lc.
lc.

Reputation: 116528

It's a little ugly, but I've had some success inheriting from ToolStripDropDown, which then contains arbitrary content via a ToolStripControlHost. Pass your content (UserControl, Panel, or some other container) to the contructor of ToolStripControlHost and add this to ToolStripDropDown.Items.

The two ugly parts are:

  • It may not autosize itself well, so be prepared to handle sizing yourself. The easiest way is to set MinimumSize and MaximumSize of the ToolStripDropDown to the size of the contents. Also there is also no inbuilt way for users to resize the window, so you will have to implement this as well if needed.
  • Some controls do not behave well inside the ToolStripDropDown. As soon as they take focus the entire thing things you've clicked elsewhere and it disappears. Examples are ComboBox and DateTimePicker. You can get around this by calling SuspendMenuMode on and ResumeMenuMode on the internal class System.Windows.Forms.ToolStripManager+ModalMenuFilter. You will need to find this type and invoke these two methods using reflection.

The following resources may be of additional help:

Upvotes: 0

Related Questions