質問

I'm experiencing some really weird behavior with MenuStrip:

  1. Create a new WinForms project (.net 4.0. C# or VB.NET doesn't matter; I used C#).
  2. Drop a 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.
  3. Drop a OpenFileDialog on your form as well.
  4. 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);
        }
    }
    
  5. 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.

役に立ちましたか?

解決

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().

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top