开发者

C# Create Notepad++ like Search Box

开发者 https://www.devze.com 2023-02-04 08:59 出处:网络
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 th

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)
    {
     开发者_StackOverflow中文版   // 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?


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


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 ...)


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消