C# 线程处理过程

本文关键字:过程 处理 线程 | 更新日期: 2023-09-27 18:37:02

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
   }
}

根据此代码,当我们单击登录表单中的登录事件并且isValiduser返回true时,程序.cs将运行MainInterface表单。 但实际上,这段代码不是Application.Run(new MainInterface())运行的;那么,谁能告诉我这段代码有什么问题?

C# 线程处理过程

你在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();
              this.DialogResult = DialogResult.OK;
           }
         else
           {
              //else part code
           }
        }

问题是你没有isValiduser设置为代码中的true。 因此,它将MainInterface形式运行。

假设您在程序.cs文件中定义了名为isValiduser的静态变量

static class Program
{
    public static bool isValiduser = false;
    [STAThread]
    static void Main()
    {
      // rest of your code 

然后,当您单击登录按钮时,您需要根据登录状态设置此变量。为此,您可能需要单独的方法。

private void btnLogin_Click(object sender, EventArgs e)
{
    // call validate user method and set value to `isValiduser`
    Program.isValiduser= IsValidUser("username", "password"); // here for testing i'm set it as true 
    if(Program.isValiduser== true)
    {
      this.Close();
    }
    else
    {
      //else part code
    }
}

您可以有验证用户的方法

private bool IsValidUser(string name, string pw)
{
    return true; // impliment this method 
}

我怀疑正在发生的事情是,当您到达this.Close()时,控件将返回到主线程并且应用程序结束(如果之后没有进一步的代码)。 即您的程序从主程序的第一行开始,在最后一行结束。因此,如果您先打开登录表单,则需要在关闭登录表单之前打开主界面表单。