0

I am reading the book Charles Petzold-Programming Microsoft Windows with C# in order to learn C# and .NET so I can move away from C++ and raw WinAPI. In the book there is an example that should create 2 forms as soon as program starts.

The author writes the whole program from scratch but I wish to use designer to do this. To reiterate, when program starts 2 forms must appear.

The only thing I found so far was this thread but I am not experienced enough to figure out if that is a solution to my problem.

After reading carefully and thinking for a moment, I have modified my app like this:

1.) I have right-clicked on the name of the project in the Solution Explorer and chose Add new Item;

2.) I have added new form ( it is named Form2 );

3.) I have changed Program.cs ( the one generated for me automatically ) like below ( added relevant snippet, the rest is omitted so my post can be as brief as possible ):

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    /******** this is what I have added ***********/
    Form form2 = new Form2();
    form2.Show();
    /*********************************************/

    Application.Run(new Form1());
}

When I run the program 2 forms are created. I do not notice anything unusual, like memory leaks or something similar. When I close first form the second ( form2, the one I added ) is closed too. If I close form2 first form stays.

My questions:

  • Since this is my first time with C#, can you verify the correctness of my solution? If my way is not correct can you show me the proper one?

  • How can I modify my program to close first form too, when I close the second form (I assume I need to handle second form's WM_CLOSE)?

EDIT #1:

I have handled second form's FormClosing event and added Application.Exit(); to close first form and the entire application. I am asking if this is the right way, or is this a mistake?

EDIT #2:

I am submitting author's original code so the viewers can get the better idea of what I am trying to accomplish:

using System;
using System.Drawing;
using System.Windows.Forms;

class PaintTwoForms
{
    static Form form1, form2;

    public static void Main()
    {
        form1 = new Form();
        form2 = new Form();

        // omitted irrelevant property settings ( background color, text... )

        form2.Show();
        Application.Run(form1);
    }
}

If further information is required leave a comment and I will update my post as soon as possible.

Community
  • 1
  • 1
AlwaysLearningNewStuff
  • 2,939
  • 3
  • 31
  • 84
  • What was the author's code, or are you trying to solve it without relying on it? http://stackoverflow.com/questions/15300887/run-two-winform-windows-simultaneously – Prix Oct 11 '14 at 01:41
  • @Prix: I am trying to achieve the same result. Author doesn't use form designer but codes everything from scratch. I wish to do things the usual way, by using form designer. The above snippets were my try to do the example from the book by using form designer. I hope this makes things clear now. I have also edited my post with the relevant parts of the author's code. Thank you for the link. Best regards. – AlwaysLearningNewStuff Oct 11 '14 at 11:09

2 Answers2

2

I think there is a better way listed on the same thread that you mentioned...

  1. Right Click Project -> Add -> Class -> name it MyApplicationContext
  2. MyApplicationContext Class:

    using System.Windows.Forms;
    
    class MyApplicationContext : ApplicationContext
    {
        private void onFormClosed(object sender, EventArgs e)
        {
            Application.Exit();
        }
    
        public MyApplicationContext()
        {
            //If WinForms exposed a global event that fires whenever a new Form is created,
            //we could use that event to register for the form's `FormClosed` event.
            //Without such a global event, we have to register each Form when it is created
            var forms = new List<Form>() {
            new Form1(),
             new Form2(),
             };
            foreach (var form in forms)
            {
                form.FormClosed += onFormClosed;
                form.Show();
            }
        }
    }
    

    Link

  3. Modify your Program.cs as:

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyApplicationContext());
        }
    }
    
  4. Now execute, you will have all the forms that were in the List<Form> and If you close any form of them, all the rest of the forms that were in the list will be closed, if you want to sequentially call the Form.Close() method you could also use a loop as in the code below but I think its better to Application.Exit().

    private void onFormClosed(object sender, EventArgs e)
    {
        FormCollection forms = Application.OpenForms;
        while (forms.Count > 0)
        {
            forms[0].Close();
        }
    }
    

Edit:

Yes the code that I have written above is indeed better than the code written by the author...

  • My code will create as many forms as you want, just add them in the list.
  • My code is adding the same closing method to every form so If any of the form closes all the rest will close.
  • My code will be more readable, For example if you are trying the same thing for 10 or more Forms The author's code will be very hard to read where as my code will be more readable.
Community
  • 1
  • 1
Syed Farjad Zia Zaidi
  • 3,302
  • 4
  • 27
  • 50
  • I had a feeling that this might be the best way but wasn't sure... I have updated my post with relevant portion of author's code. That is what I'm trying to achieve. Author codes everything from scratch, but I wish to achieve the same result by using form designer. Can you take a look at the updated part of my post so you can confirm that we are "on the same page"? Thank you. Best regards. – AlwaysLearningNewStuff Oct 11 '14 at 11:17
  • @AlwaysLearningNewStuff Yes I think code written above is better than the author's code, check my edited answer and Please mark it as answer and up vote if this was helpful... – Syed Farjad Zia Zaidi Oct 11 '14 at 12:29
  • I think you are right, since the example is taken from the very start of the book. Author made that small program to illustrate something else. I like the above approach, and I agree with you that it is cleaner. I am officially accepting and upvoting your answer. Thank you. Best regards. – AlwaysLearningNewStuff Oct 11 '14 at 14:35
  • [Plagiarism is the sincerest form of flattery.](http://stackoverflow.com/a/13406508/111794). @AlwaysLearningNewStuff – Zev Spitz Sep 15 '15 at 20:38
0

You can show 2 Form instead of 1 by typing this:

    private void Form1_Load(object sender, EventArgs e)
    {
            Form2 f2 = new Form2();
            f2.Show();
    }

You can add this code to hide form:

    this.Hide();
Pouya
  • 109
  • 1
  • 8
  • Thank you for helping. I came to this idea too, but wasn't sure if it will work. Will I be able to achieve the desired behavior when I close second form with your solution ( I have described the behavior in detail in my post )? Best regards. – AlwaysLearningNewStuff Oct 11 '14 at 11:20