当前位置: 动力学知识库 > 问答 > 编程问答 >

C# - Application continues running in the background when closing it after an another form was opened

问题描述:

When I click on About, a new form opens and the main form hides. I have a close button on the About button, that closes the About form, and it shows up the Main form. However, when I close the main form with the 'X' close button on top, the Main form closes, but the process is still running in the background. Everything is okay when I dont click on the About button. It kills the process.

网友答案:

In your Form2, you need to bring up the existing Form1 instance rather than creating a new one (that's why closing this newly created Form1 won't exit the application, as your old Form1 instance is still hiding...). So you could get reference passed when creating aboutdialog, and show that instead when closing aboutdialog:

Form1:

private void AboutButton_Click(object sender, EventArgs e)
        {
            var aboutdialog = new Form2(this);
            aboutdialog.Show();
            this.Hide();
        }

Form2:

Form1 _parentform;
public Form2(Form1 parent)
        {
            _parentform=parent;
            InitializeComponent();
        }



private void CloseButton_Click(object sender, EventArgs e)
        {
            _parentform.Show();
            this.Close();
        }
网友答案:

In your "AboutButton_Click" method you hide the Form1. But when closing the About dialog, you do not show back the Form1, but create a new one. The original Form1 stays hidden and prevents your application from closing.

网友答案:

better to use showdialog.

private void AboutButton_Click(object sender, EventArgs e)
{
    var aboutdialog = new Form2();
    aboutdialog.ShowDialog();
}
网友答案:

When form2 is closed a new instance of form1 is opened, instead of the original one. You could include a reference to Form1 inside of Form2, or use the default Ownerof a form, by showing the dialog with Form1 as its owner:

aboutdialog.Show(this);

in the about...click

and closing

  private void CloseButton_Click(object sender, EventArgs e)
        {
            Owner.Show(); 
            this.Close();
        }
分享给朋友:
您可能感兴趣的文章:
随机阅读: