Question

I am building a kind of prototype for a MDI application. I have a main form, called mainForm, and some other child forms, all instances of a childForm class. These instances of my childForm class have all a basic MenuStrip, with some form\close, print, etc toolStripMenuItems.

At click time, how can I identify which instance of the childForm class is holding the activated toolStripMenuItem?

EDIT: following dash comment

The pseudo-code looks like this:

Form myNewForm = new Form()
MenuStrip myNewMenu = new MenuStrip()
...
myNewForm.Controls.Add(myNewMenu)
myNewForm.MainMenuStrip = myNewMenu
Was it helpful?

Solution

Given my original comment, and your update, the following works for me:

  Form newChildForm = new Form();
  newChildForm.Name = "ChildForm";
  MenuStrip newMenu = new MenuStrip();

  ToolStripItem newItem = newMenu.Items.Add("New Item");
  newItem.Click += new EventHandler(newItem_Click);

  newChildForm.Controls.Add(newMenu);
  newChildForm.MainMenuStrip = newMenu;

  newChildForm.Show();

Then, in the event handler:

void newItem_Click(object sender, EventArgs e)
{
  ToolStripItem clickedItem = sender as ToolStripItem;

  MenuStrip parentMenu = clickedItem.Owner as MenuStrip;

  Form childForm = parentMenu.FindForm() as Form;
  //childForm.Parent is also "ChildForm";

}

Are you doing anything differently?

OTHER TIPS

Kudos to dash, that should have been posted as an answer.

Im going to assume that you are inside the click event of the menu item...

Control s = sender as Control;//the sender object from the click event
ChildForm activeForm = s.FindForm() as ChildForm;

This would give the specific instance of the form you are looking for.

alternatively, the button click event SHOULD be implemented from the ChildForm class itself, which would mean that during any click event, your "this" operator should in fact BE the specific instance of The ChildForm class being activated.

ChildForm activeForm = this;

which is an entirely unnecessary assignment but does illustrate the point. This would not be true if your menu strip was located on some other custom user control container, in which case you would need something like this.

ChildForm activeForm = this.ParentForm;

the ParentForm property is unique to 'ContainerControl' which is defined as a control which can contain other controls, and it identifies the base 'form' on which the container is being displayed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top