C#:从单独的表单中关闭和打开两个表单 [英] C#: Close and Open two forms from a separate form
问题描述
我有3种形式.我该如何做,以使一种形式显示为.Show(),而另一种形式隐藏为.Hide()呢?又是另一种形式?
I have 3 forms. How can I make it so that one form is shown with .Show() and the other is hidden with .Hide() from a separate form?
这是我的代码的一部分
private void buttonYes_Click(object sender, EventArgs e)
{
LoggedIn loggedinform = new LoggedIn();
loggedinform.Hide(); // Hides another form that is in the background
MainForm mainform = new MainForm();
mainform.Show(); // Show first form
this.Hide(); // Hides current form
}
一个问题,LoggedIn表单不会隐藏自身.从它的外观来看,它跳过了它,只是去了mainform.Show();
One problem, the LoggedIn form does not hide itself. From the looks of it it skips it and just goes for the mainform.Show();
这是一个错误还是我需要做其他事情?
Is this a bug or do I need to do something else?
推荐答案
LoggedIn loggedinform = new LoggedIn()
行将创建该登录窗口的新实例.例如,如果您打算一次在屏幕上显示5个登录"窗口,则这可能会很有用.我认为您想要做的就是检索对已经显示的登录窗口的引用,并将其隐藏;因此,避免创建一个新的.
The line LoggedIn loggedinform = new LoggedIn()
is going to create a new instance of that login window. That might be useful if, say, you intended to show 5 "Login" windows onscreen all at once. I think what you want to do is retrieve a reference to the login window that is already showing, and hide that; so, avoid creating a new one.
在程序周围正确传递对现有对象的引用是一种结构性问题,在我早期的编程时代,我遇到了很多问题.一种快速,不干净且通常不推荐的方法是将这些单个对象(例如,您的登录窗口)的实例声明为static
,以便可以在任何地方检索它们.但是,为了以最佳方式完全回答您的问题,也许您可以描述一下程序的结构(完整的代码不是必需的,一般来说,类之间的流程是没有必要的)
Properly passing references to existing objects around the program is kind of a structural problem, and one that I ran into quite a bit in my early programming days. The quick, unclean, and generally not-recommended way is to declare instances of those singular objects (like, maybe, your login window) as static
, so they can be retrieved anywhere. However, to fully answer your question in the best way, maybe you could describe the structure of your program a bit more (full code isn't necessary, just generally-speaking, what the flow is between classes)
这篇关于C#:从单独的表单中关闭和打开两个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!