I see two different way that I would choose between for this problem.
If you could think of hosting the command in a MenuStrip
instead, and it is the same child form that lives in several instances in the MDI application, you could add the command(s) to a MenuStrip
control in the child form instead. These menu commands will be automatically merged with the commands in the parent form, but any click events will be carried out in the active child form.
You can control where and how menu commands from the child form merges with the commands in the parent form through the MergeAction
and MergeIndex
properties. If using this approach you should probably set the Visible
property of the MenuStrip
in the child form to false
to prevent it from taking up unnecessary space on the form.
The second option that I would suggest is to create an interface for defining the search functionality, implement that interface in the child forms that support it, and use the MdiChildActivate
event of the MDI parent form to enable or disable the search function based on whether the current child supports it or not.
Simplified code sample of the second approach:
interface IGridSearch
{
void PerformSearch(string criteria);
}
public partial class MdiChildUI : Form, IGridSearch
{
public MdiChildUI()
{
InitializeComponent();
}
public void PerformSearch(string criteria)
{
// peform the search
}
}
public partial class MdiParentUI : Form
{
public MdiParentUI()
{
InitializeComponent();
}
private void MdiParentUI_MdiChildActivate(object sender, EventArgs e)
{
SetControlStates();
}
private void SetControlStates()
{
_searchCommand.Enabled = (this.ActiveMdiChild is IGridSearch);
}
private void _searchCommand_Click(object sender, EventArgs e)
{
IGridSearch child = (this.ActiveMdiChild as IGridSearch);
if (child != null)
{
child.PerformSearch("whatever to search for");
}
else
{
MessageBox.Show("Can't search in the active form");
}
}
}