在应用程序中显示隐藏表单

时间:2012-06-09 08:09:35

标签: c# winforms

我在Window Form Application中显示或隐藏表单有问题。

我首先在program.cs上运行loginform(Application.Run(new loginform());),当登录成功时,然后显示另一个表单(主界面),我想在显示第二个表单时关闭或隐藏loginform ,但它没有用。

我不知道该怎么做。它是否与线程相关?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Myapp
{
   static class Program
   {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Loginfrm());

        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以向Loginfrm类添加一个属性,指示登录是否成功。 然后,在关闭Loginfrm之后,您可以启动另一个消息循环。

示例:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Loginfrm login = new Loginfrm(); 
    Application.Run(login);
    if (login.LogInSuccesfull)
        Application.Run(new MainForm());
}

答案 1 :(得分:0)

// in the mainform add to project form and call it SubForm
SubForm subform = new Subform();
subform.Show();
// in the subform
subform.Close();

答案 2 :(得分:0)

使用Singleton

MainInterface.cs

using System;

public class MainInterface : Form
{
   private static MainInterface Current;

   private MainInterface ()
   {
      if ( LoginForm . Instance != null )
         LoginForm . Instance . Close ();
   }

   public static MainInterface Instance
   {
      get 
      {
         if (Current == null)
         {
            Current = new MainInterface ();
         }
         return Current;
      }
   }
}

<强> LoginForm.cs

using System;

public class LoginForm: Form
{
   private static LoginForm Current;

   private LoginForm ()
   {

      if ( MainInterface . Instance != null )
         MainInterface . Instance . Close ();
   }

   public static LoginForm Instance
   {
      get 
      {
         if (Current == null)
         {
            Current = new LoginForm ();
         }
         return Current;
      }
   }
}

<强> Program.cs的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Myapp
{
   static class Program
   {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            LoginForm . Instance . ShowDialog ();

        }
    }
}

切换表单

来自LoginForm

LoginForm . Instance . Hide ();
MainInterface . Instance . ShowDialog ();

来自MainInterface

MainInterface . Instance . Hide ();
LoginForm . Instance . ShowDialog ();

对于更多2个表单,我建议使用Manager类(例如Process)来管理和切换它们:)

此致