c#打开一个新表格然后关闭当前表格?

时间:2011-04-05 07:45:38

标签: c# winforms forms

例如,假设我在表单1然后我想:

  1. 打开表单2(来自表单1中的按钮)
  2. 关闭表单1
  3. 专注于表格2

15 个答案:

答案 0 :(得分:154)

史蒂夫的解决方案不起作用。调用this.Close()时,当前表单与form2一起处理。因此,您需要隐藏它并设置form2.Closed事件来调用this.Close()。

private void OnButton1Click(object sender, EventArgs e)
{
    this.Hide();
    var form2 = new Form2();
    form2.Closed += (s, args) => this.Close(); 
    form2.Show();
}

答案 1 :(得分:18)

尝试这样做......

{
    this.Hide();
    Form1 sistema = new Form1();
    sistema.ShowDialog();
    this.Close();
}

答案 2 :(得分:10)

其他答案已经描述了许多不同的方式。但是,他们中的许多人要么ShowDialog(),要么form1保持开放但隐藏。在我看来,最好和最直观的方法是简单地关闭form1,然后从外部位置创建form2(即不是从这些形式中的任何一个内)。在form1中创建Main的情况下,可以使用form2创建Application.Run,就像form1之前一样。这是一个示例场景:

我需要用户输入他们的凭据,以便我以某种方式对他们进行身份验证。之后,如果身份验证成功,我想向用户显示主应用程序。为了实现这一目标,我使用了两种形式:LogingFormMainFormLoginForm有一个标志,用于确定身份验证是否成功。然后使用此标志来决定是否创建MainForm实例。这些形式都不需要知道另一种形式,两种形式都可以优雅地打开和关闭。这是以下代码:

class LoginForm : Form
{
    bool UserSuccessfullyAuthenticated { get; private set; }

    void LoginButton_Click(object s, EventArgs e)
    {
        if(AuthenticateUser(/* ... */))
        {
            UserSuccessfullyAuthenticated = true;
            Close();
        }
    }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        LoginForm loginForm = new LoginForm();
        Application.Run(loginForm);

        if(loginForm.UserSuccessfullyAuthenticated)
        {
            // MainForm is defined elsewhere
            Application.Run(new MainForm());
        }
    }
}

答案 3 :(得分:9)

问题在于那条线:

Application.Run(new Form1()); 这可能在program.cs文件中找到。

此行表示form1用于处理消息循环 - 换句话说,form1负责继续执行您的应用程序 - 当form1关闭时,应用程序将被关闭。

有几种方法可以解决这个问题,但所有这些方法都不会以某种方式关闭.1 (除非我们将项目类型更改为Windows窗体应用程序以外的其他内容)

我认为最简单的方法是创建3种形式:

  • form1 - 将保持不可见并充当经理,如果需要,您可以指定它来处理托盘图标。

  • form2 - 将有一个按钮,单击该按钮将关闭form2并将打开form3

  • form3 - 将具有需要打开的其他表单的角色。

以下是完成该操作的示例代码:
(我还添加了一个从第3版关闭应用程序的示例)

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1()); //set the only message pump to form1.
    }
}


public partial class Form1 : Form
{
    public static Form1 Form1Instance;

    public Form1()
    {
        //Everyone eveywhere in the app should know me as Form1.Form1Instance
        Form1Instance = this;

        //Make sure I am kept hidden
        WindowState = FormWindowState.Minimized;
        ShowInTaskbar = false;
        Visible = false;

        InitializeComponent();

        //Open a managed form - the one the user sees..
        var form2 = new Form2();
        form2.Show();
    }

}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var form3 = new Form3(); //create an instance of form 3
        Hide();             //hide me (form2)
        form3.Show();       //show form3
        Close();            //close me (form2), since form1 is the message loop - no problem.
    }
}

public partial class Form3 : Form
{
    public Form3()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1.Form1Instance.Close(); //the user want to exit the app - let's close form1.
    }
}


注意:使用面板或动态加载用户控件更具学术性,更适合作为行业生产标准 - 但在我看来,您只是试图推断出事情的工作原理 - 为此目的,这个例子更好。

现在理解这些原则让我们只用两种形式来尝试:

  • 第一个表单将扮演管理员的角色,就像上一个示例一样,但也会显示第一个屏幕 - 所以它不会被隐藏起来。

  • 第二种形式将扮演显示下一个屏幕的角色,单击按钮将关闭该应用程序。


    public partial class Form1 : Form
    {
        public static Form1 Form1Instance;

        public Form1()
        {
            //Everyone eveywhere in the app show know me as Form1.Form1Instance
            Form1Instance = this;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Make sure I am kept hidden
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Visible = false;

            //Open another form 
            var form2 = new Form2
            {
                //since we open it from a minimezed window - it will not be focused unless we put it as TopMost.
                TopMost = true
            };
            form2.Show();
            //now that that it is topmost and shown - we want to set its behavior to be normal window again.
            form2.TopMost = false; 
        }
    }

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form1.Form1Instance.Close();
        }
    }

如果您更改上一个示例 - 从项目中删除form3。

祝你好运。

答案 4 :(得分:6)

你并不具体,但看起来你正试图在我的Win Forms应用程序中做我做的事情:从登录表单开始,然后在成功登录后,关闭该表单并将焦点放在主表单上。我是这样做的:

  1. 使frmMain成为启动形式;这就是我的Program.cs的样子:

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new frmMain());
    }
    
  2. 在我的frmLogin中,创建一个初始化为false的公共属性,只有在成功登录时才设置为true:

    public bool IsLoggedIn { get; set; }
    
  3. 我的frmMain看起来像这样:

    private void frmMain_Load(object sender, EventArgs e)
    {
        frmLogin frm = new frmLogin();
        frm.IsLoggedIn = false;
        frm.ShowDialog();
    
        if (!frm.IsLoggedIn)
        {
            this.Close();
            Application.Exit();
            return;
        }
    
  4. 没有成功登录?退出应用程序。否则,继续使用frmMain。由于它是启动形式,当它关闭时,应用程序结束。

答案 5 :(得分:1)

在form1中使用此代码段。

public static void ThreadProc()
{
Application.Run(new Form());
}

private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}

我是从here

得到的

答案 6 :(得分:1)

如果您有两种形式:frm_form1和frm_form2。以下代码用于打开frm_form2并关闭frm_form1。(对于Windows窗体应用程序)

        this.Hide();//Hide the 'current' form, i.e frm_form1 
        //show another form ( frm_form2 )   
        frm_form2 frm = new frm_form2();
        frm.ShowDialog();
        //Close the form.(frm_form1)
        this.Close();

答案 7 :(得分:1)

我通常这样做是为了在表单之间来回切换。

首先,在 Program 文件中,保留 ApplicationContext 并添加一个帮助器 SwitchMainForm 方法。

        static class Program
{
    public static ApplicationContext AppContext { get;  set; }


    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        //Save app context
        Program.AppContext = new ApplicationContext(new LoginForm());
        Application.Run(AppContext);
    }

    //helper method to switch forms
      public static void SwitchMainForm(Form newForm)
    {
        var oldMainForm = AppContext.MainForm;
        AppContext.MainForm = newForm;
        oldMainForm?.Close();
        newForm.Show();
    }


}

然后在代码中的任意位置,我调用 SwitchMainForm 方法以轻松切换到新表单。

// switch to some other form
var otherForm = new MyForm();
Program.SwitchMainForm(otherForm);

答案 8 :(得分:0)

假设您有两个表单,第一个表单名称是Form1,第二个表单名称是Form2。您必须从Form1跳转到Form2,在此处输入代码。编写如下代码:

在Form1上我有一个名为Button1的按钮,在其单击选项上写下代码:

protected void Button1_Click(Object sender,EventArgs e)
{
    Form frm=new Form2();// I have created object of Form2
    frm.Show();
    this.Visible=false;
    this.Hide();
    this.Close();
    this.Dispose();
}

希望此代码可以帮助您

答案 9 :(得分:0)

private void buttonNextForm(object sender, EventArgs e)
{
    NextForm nf = new NextForm();//Object of the form that you want to open
    this.hide();//Hide cirrent form.
    nf.ShowModel();//Display the next form window
    this.Close();//While closing the NextForm, control will come again and will close this form as well
}

答案 10 :(得分:0)

//if Form1 is old form and Form2 is the current form which we want to open, then
{
Form2 f2 = new Form1();

this.Hide();// To hide old form i.e Form1
f2.Show();
}

答案 11 :(得分:0)

此代码可以帮助您:

Master frm = new Master();

this.Hide();

frm.ShowDialog();

this.Close();

答案 12 :(得分:0)

                     this.Visible = false;
                        //or                         // will make LOgin Form invisivble
                        //this.Enabled = false;
                         //  or
                       // this.Hide(); 



                        Form1 form1 = new Form1();
                        form1.ShowDialog();

                        this.Dispose();

答案 13 :(得分:0)

我认为这更容易:)

    private void btnLogin_Click(object sender, EventArgs e)
    {
        //this.Hide();
        //var mm = new MainMenu();
        //mm.FormClosed += (s, args) => this.Close();
        //mm.Show();

        this.Hide();
        MainMenu mm = new MainMenu();
        mm.Show();

    }

答案 14 :(得分:-3)

我会这样做:

private void button1_Click(object sender, EventArgs e)
{
    Form2 m = new Form2();
    m.Show();
    Form1 f = new Form1();
    this.Visible = false;
    this.Hide();
}
相关问题