方法 this.hide() 与 this.close() [英] Methods this.hide() vs this.close()

查看:40
本文介绍了方法 this.hide() 与 this.close()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 c# windows 窗体应用程序有 5 个窗体,我一个接一个地显示.当用户点击下一步按钮时,我给出的代码是:

My c# windows forms application has 5 forms which I am displaying one after the another. When the user clicks on next button, the code I have given is:

new Form1().Show();
this.Hide();

但是我不想隐藏我当前的表单.我想关闭它/处理它,这样它就不会消耗内存.我想在完成后立即释放其资源,例如使用的图像和变量.为此,我尝试实施:

However I do not want my current Form to hide. I want to close it/dispose it so that it does not consume memory. I want to release its resources like the images and variable used as soon as I am done with it. For that I tried implementing:

new Form1().Show();
this.Close();    //Form 2

但这只是关闭了两个表单.我什至尝试交换上面两行的位置:

but this simply closes both the forms. I even tried swapping the positions of the above two lines:

this.Close();
new Form1().Show();

但这也做同样的事情.

如何在完成一个表单后立即释放它的资源?因为当我尝试使用以下方法重新打开 Form 2 时,我的程序抛出内存不足异常:

How do I release the resources of one form as soon as I am done with it? because my program throws out of memory exception when I try to re-open my Form 2 using:

new Form2().Show();
this.Hide();

推荐答案

你可以在一个新的 thread 中启动你的 NewForm 并创建一个新的消息循环

You can start your NewForm in a new thread and create a new message loop

当主消息循环关闭时,应用程序退出.在 Windows Forms 中,这个循环在调用 Exit 方法时关闭

When the main message loop is closed, the application exits. In Windows Forms, this loop is closed when the Exit method is called

有关详细信息,请参阅此处.

For more information see here.

var th = new Thread(() => Application.Run(new NewForm()));
th.SetApartmentState(ApartmentState.STA); // Deprecation Fix
th.Start();

this.Close();

这篇关于方法 this.hide() 与 this.close()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆