Nourelhouda
Nourelhouda

Reputation: 11

Close current form and open new form and then return

I want to click button and go to FormSetting, and close current FormMain. When I'm done working on FormSetting, I want to click the back button and go back to FormMain.

//FormSetting
private void ButtonSetting_Click(object sender, EventArgs e)
{
    this.Hide();
    FormSetting formsetting = new FormSetting();
    formsetting.SetPrevForm(this);
    // OpenSeconderyForm(formsetting);
    formsetting.ShowDialog();
}


//FormMain
public void SetPrevForm(Form f)
{
    formMain = f;
}


private void toolStripButton8_Click(object sender, EventArgs e)
{
    this.Hide();
    formMain.ShowDialog();
}

Upvotes: 0

Views: 129

Answers (1)

IV.
IV.

Reputation: 9463

Your code has a main form and a settings form. When the settings form is shown, your code is attempting to hide the main form. When the Button8 on the ToolStrip in your settings form is clicked, your code tries to close the settings form and make the main form visible again. I will offer a few basics and you can modify them to your requirements. So let's start with minimal representations of your two forms:

show either the main form or the settings form


Clicking the [Settings] button

The "trick" here is that when you call ShowDialog for your settings form, pass the this keyword. That will set the Owner property of your settings form to point to the main form.

public partial class MainForm : Form
{
    public MainForm() => InitializeComponent();

    private void buttonSettings_Click(object sender, EventArgs e)
    {
        _settings.ShowDialog(this);
    }
    SettingsForm _settings = new SettingsForm();
}

Hiding the main form when the settings is shown

By overriding the OnVisibleChanged method in your settings form, the visibility of the main form can now be manipulated using the Owner property. When Button8 is clicked, it closes the settings dialog which causes the Visible property to change to false. The OnVisibleChanged override will detect this so that the main form can be made visible again using the Owner property.

public partial class SettingsForm : Form
{
    public SettingsForm() => InitializeComponent();

    protected override void OnVisibleChanged(EventArgs e)
    {
        if(Visible)
        {
            Owner?.Hide();
        }
        else
        {
            Owner?.Show();
        }
        base.OnVisibleChanged(e);
    }

    private void toolStripButton8_Click(object sender, EventArgs e) => Close();
}

Upvotes: 2

Related Questions