Reputation: 20137
What I'm trying to make is a search window exactly the same as in VS or Notepad++, where both windows are active (because the FindBox is shown with Show not ShowDialog), and when you press find in the FindBox, the parent performs the search. Here's an example:
class MainForm : Form
{
public void FindNext(string find)
{
// Do stuff
}
public void OpenFindWindow()
{
FindBox find = new FindBox();
find.customParent = this;
find.Show();
}
}
class FindBox : Form
{
public customParent;
public void FindButtonPressed()
{
((MainForm)customParent).FindNext(textBox1.text);
}
}
But it seems strange I have to manually set this new field "customParent". What is the official way to do something like this?
Upvotes: 3
Views: 1754
Reputation: 29174
You could use
find.Show(this);
and use the Owner
property of find
to access the parent form. Of course you'll have to cast it to MainForm
in this case:
((MainForm)this.Owner).FindNext(textBox1.Text);
This approach also has the advantage that the main form cannot hide the find box (owned forms will always be displayed on top of their owners, even if the owner has the focus ...)
Upvotes: 1
Reputation: 49225
You can use owner form - use Show overload that accepts owner form. And then use Form.Owner property to get reference to owner form. You need to case the owner form to specific form type creating tight coupling (but of course, you can introduce an interface to loosen that up).
Upvotes: 1
Reputation: 30131
You can either accept the customParent as a argument in the constructor, or better yet, the FindBox
form should take a Action<string>
that it will call once the find button is pressed.
class MainForm : Form
{
public void FindNext(string find)
{
// Do stuff
}
public void OpenFindWindow()
{
FindBox find = new FindBox(this.FindNext);
find.Show();
}
}
class FindBox : Form
{
private Action<string> callback;
public FindBox(Action<string> callback)
{
this.callback = callback;
}
public void FindButtonPressed()
{
callback(textBox1.text);
}
}
Upvotes: 2