C # Create Notepad ++ as a search field

What I'm trying to do is a search box, exactly the same as in VS or Notepad ++, where both windows are active (because FindBox is displayed with Show ShowValog), and when you click find on FindBox, the parent searches. Here is 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 to me that I need to manually set this new "customParent" field. What is the official way to do something like this?

+3
source share
3 answers

you can use

find.Show(this);

and use the property Ownerto findaccess the parent form. Of course, in this case you need to drop it on MainForm:

((MainForm)this.Owner).FindNext(textBox1.Text);

, ( , ...)

+1

customParent , , , FindBox Action<string>, .

:

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);
    }
}
+2

You can use the owner form - use Show overload , which takes the owner form. And then use the Form.Owner property to get a link to the owner form. You need to specify the owner form for a particular type of form, creating a tight connection (but, of course, you can enter an interface to ease this).

+1
source

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


All Articles