Reputation: 35400
I'm experiencing some really weird behavior with MenuStrip:
MenuStrip
on the default form. Right-click and choose Insert Standard Items to quickly build it for you. This step could be done manually as well.OpenFileDialog
on your form as well.Add an event handler for DropDownItemClicked
event of the File menu. Add the following code into it:
private void fileToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Name == "openToolStripMenuItem")
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
MessageBox.Show(openFileDialog1.FileName);
}
}
Run the project. Click on File menu and then Open command. The file dialog appears BUT, the File menu doesn't disappear. In fact it draws on top of the OpenFileDialog
, hiding some part of it. After you click Open or Cancel in the dialog, both the dialog and the File menu will go away.
Why is this so? Is this a known bug or feature? I also checked that this doesn't happen for my dialog boxes, only for the built-in dialogs. You have to manually call FileToolStripMenuItem.HideDropDown()
before showing built-in dialogs.
Upvotes: 4
Views: 2989
Reputation: 63317
It's not a bug. It's a feature.
In fact the drop down menu will be hidden automatically after the code executing in the DropDownItemClicked
event handler. However you use some kind of MessageBox
or ShowDialog
which will block the current execution and hang the drop down menu there.
There are at least 2 solutions for you to solve this, one is hide the menu yourself before showing the Dialog (this seems to be adopted by you). The another solution is using BeginInvoke
to show your dialog, that async
call won't block the current execution and the drop down menu will be hidden expectedly:
private void fileToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e){
if (e.ClickedItem.Name == "openToolStripMenuItem")
{
BeginInvoke((Action)(()=>{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
MessageBox.Show(openFileDialog1.FileName);
}));
}
}
NOTE: to hide the drop down menu
manually in the DropDownItemClicked
event handler, you can use e.ClickedItem.Owner.Hide()
instead of FileToolStripMenuItem.HideDropDown()
.
Upvotes: 4