开发者

Windows forms spinning in c#

开发者 https://www.devze.com 2023-01-15 01:25 出处:网络
I have two windows forms.Now I have to close first one and show the second form and vice开发者_Go百科-versa.How can i do it.I was passing this pointer to the constructor of second form and then trying

I have two windows forms.Now I have to close first one and show the second form and vice开发者_Go百科-versa.How can i do it.I was passing this pointer to the constructor of second form and then trying to close it,but this did not work.I can not use showdialog here.


Add static variables to each form in the Program class:

static class Program
{
    public static Form1 f1=null;
    public static Form2 f2 = null;

    public static FullClose=false;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        f1=new Form1();
        f2 = new Form2();

        Application.Run(f1);
    }
}

Then in the Form_Closing event of each form:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (Program.FullClose==false)
    {
       e.Cancel = true;
       this.Visible = false;

       Program.f2.Show();
    }
}

(Change Program.f2.Show() to Program.f1.Show() in Form2).

Of course this will stop the application from ever closing, so you should provide an extra button (or similar) that sets a boolean static variable (FullClose) that the Form_Closing events can check to see if they should properly close or not.


You must set in your application, the close is not then main form was closed, then if all forms all closed.

You must pass the pointer of the main form to second form and main form must have second form pointer.

Then implement in your forms OnClosing event, then in her implementation open other form if this success return, else set Cancel to true and return.


In every case there is one form, which represents the live of your application. This form will be started within your Program.cs file by calling

Application.Run(new MyForm());

If you try to start within this form another one and this will afterwards kill his creator, this will always lead to some bad designs.

Instead you should create some super-form. It is invisible and contains the glue code between those two forms. Right after startup it creates both forms and shows the first one. Also it registers to an (self-written) event in both forms which claims to show the other one. If your invisible form gets the event from one form it just makes the sender invisible and shows up the other one.

Last but not least you need in both (or at least in one) forms a second event, which will close the super form thous closing the application.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号