如何在C#应用程序中切换主线程

时间:2012-06-13 08:14:44

标签: c# winforms

如何分开线程?

我首先使用实例运行LoginForm.cs,所以,我的第一个应用程序中的Thread是LoginForm.cs文件,但是我不想再运行LoginForm.cs的线程了,之后登录成功了,我希望我的应用程序在MainInterface.cs中运行Main Thread,这意味着,第一个Thread运行LoginForm.cs,然后在LoginForm.cs上停止Thread,在更正登录后,Thread在MainInterface.cs中运行。

我遵循以下代码,但LoginForm.cs仍然是主线程:

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 ();

        }
    }
}

1 个答案:

答案 0 :(得分:0)

<强> Program.cs的

using (Login login = new Login())
        { 
            login.ShowDialog(); //Close this form after login is correct in login form button_click
        }
        if (isValiduser == true) //Static variable created in application to check user
        {           
             Application.Run(new MainInterface());

        }

登录表单点击活动

    private void btnLogin_Click(object sender, EventArgs e)
            {
              if(isValiduser == true)
               {
                  this.Close();
               }
             else
               {
                  //else part code
               }
            }