Get click event on menu element with subitems (C #)

I create a context menu that should contain a list of all folders, subfolders and files in the selected folder. I want the menu to open files and folders when pressed, but the click event is not logged if there are sub-items in the menuitem element.

void Foo(string Title)
{
    MenuItem = new MenuItem(Title);
    MenuItem.Click += new EventHandler(MenuItem_Click);
    ContextMenu.MenuItems.Add(MenuItem);
}

void MenuItem_Click(object sender, EventArgs e)
{
    MessageBox.Show("This box will only show when menuitems without subitems are clicked");
}

How can I fire a click event even if the menuitem element has subitems?

+3
source share
2 answers

, . , , , , , , - .

, .

MenuItem.Click:

. MenuItems MenuItem , . .

+4

, .

  override protected void OnItemClicked(ToolStripItemClickedEventArgs e)
  {
    if (this.Items.Count == 0)
      base.OnItemClicked(e);

    // else do nothing
  }

ContextMenu OnItemClicked, onPopup. , ContextMenu

public class MyContextMenu : ContextMenu
{
  override protected void OnPopUp(EventArgs e)
  {
        if (this.MenuItems.Count == 0)
          base.OnPopUp(e);

        // else do nothing
  }
}

, show

public class MyContextMenu : ContextMenu
{
  override protected void Show (Control c, Point p)
  {
        if (this.MenuItems.Count == 0)
          base.Show (c, p) ;

        // else do nothing
  }

  override protected void (Control c, Point p, LeftRightAlignment z) 
  {
        if (this.MenuItems.Count == 0)
          base.Show (c, p, z) ;

        // else do nothing
  }
}
+1

Source: https://habr.com/ru/post/1714720/


All Articles