Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create Notepad++ like Search Box

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?

like image 620
Migwell Avatar asked May 07 '26 02:05

Migwell


1 Answers

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.

Example:

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);
    }
}
like image 158
The Scrum Meister Avatar answered May 09 '26 16:05

The Scrum Meister