[英]Switching between multiple forms in C#
I'm developing a C# (compact framework) app which and I need to have 3 forms. 我正在开发一个C#(紧凑框架)应用程序,并且我需要3种形式。 I can go from form1 (main) to form2, and from form1 to form3.
我可以从form1(主)转到form2,也可以从form1转到form3。 I also want to be able to switch from form2 to form3.
我还希望能够从Form2切换到Form3。 Form3 must be always the same (I need to create it when app starts and close it when app ends).
Form3必须始终相同(我需要在应用程序启动时创建它,并在应用程序结束时关闭它)。
On form1, on "Go to form 2" button 在窗体1,在“转到窗体2”按钮上
form2.Show(); form2.BringToFront();
On form1, on "Go to form 3" button 在窗体1,在“转到窗体3”按钮上
form3.Show(); form3.BringToFront();
On form2, on "Back to form 1" 在窗体2,在“返回到窗体1”上
this.Hide();
On form3, on "Back to form 1" 在form3,在“返回到窗体1”
this.Hide();
But how to switch from form2 to form3 ? 但是如何从Form2切换到Form3?
Thank you for any help! 感谢您的任何帮助!
I think there's a multi part solution here. 我认为这里有一个多部分的解决方案。
Thanks for the all the contributions! 感谢您的所有贡献! I ended up building a flexible solution that can be extended to many forms.
我最终构建了一个灵活的解决方案,可以扩展为多种形式。
When the app starts I create all the required forms. 应用启动时,我将创建所有必需的表单。 I have an auxiliary class with a (global) variable that holds the current active form (I've used an int but it could be a string with the form name).
我有一个带有(全局)变量的辅助类,该变量保存当前的活动表单(我使用了int,但是它可以是表单名称的字符串)。
static class GlobalClass
{
private static int m_currentActiveForm = 1;
public static int currentActiveForm
{
get { return m_currentActiveForm; }
set { m_currentActiveForm = value; }
}
}
On form1 I have included a timer that checks every 100ms the var currentActiveForm. 在form1上,我包括一个计时器,该计时器每100毫秒检查一次var currentActiveForm。 When a change is detected the corresponding form is displayed.
当检测到更改时,将显示相应的表格。
private void timer2_Tick(object sender, EventArgs e)
{
if (GlobalClass.currentActiveForm != lastActiveForm)
{
switch (GlobalClass.currentActiveForm)
{
case 1:
form2.Hide();
form3.Hide();
this.BringToFront();
break;
case 2:
form2.Show();
form2.BringToFront();
break;
case 3:
form3.Show();
form3.BringToFront();
break;
}
}
}
Then, on any form, to switch to a new form, I just need to assign a new value to GlobalClass.currentActiveForm which is visible in all forms. 然后,在任何表单上,要切换到新表单,我只需要为GlobalClass.currentActiveForm分配一个新值即可在所有表单中看到。
On form2, click "Go to form 3" button 在form2上,单击“转到表单3”按钮
form3.Show();
On form3, click "Back to form 2" button 在form3上,单击“返回到表单2”按钮
this.Hide();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.