Solved

C# Close MainWindow

Posted on 2011-02-10
17
933 Views
Last Modified: 2013-12-17
Hi,

I have a MainWindow, after processing from this window, I create another Window2.
However I'd like to close the MainWindow bu tkeep Window1 open.
When I close Mainwindow, the Window2 is also closed. Please help.

Thanks,
JT
0
Comment
Question by:jtran007
  • 4
  • 4
  • 2
  • +5
17 Comments
 
LVL 23

Expert Comment

by:wdosanjos
ID: 34867695
If you close the main window the application closes.  You could create a hidden main window that launches window1 and window2, that way you can close and open windows without exiting the app.

I hope this helps.
0
 

Author Comment

by:jtran007
ID: 34867846
Hi,

In WPF, I can do what I told you; but not in winform.Since I have limited memory, I
want to give back resources to window, after I use MainWindow. Your soluition still
keeps three window, eventhough one is hidden, but it still uses memory.

JT
0
 
LVL 7

Expert Comment

by:wdfdo1986
ID: 34867853
have an another window in the middle of the main window and window1. give it the main window functionalities and hide the main window.
now u can close the window like main window without closing the app.
0
 

Author Comment

by:jtran007
ID: 34867856
HI,
I should increase point value to 500 since it is not easy solution.

JT
0
 
LVL 7

Expert Comment

by:wdfdo1986
ID: 34867905
so what do u think about the given solutions.
i suggested one way of doing it.
Or u can implement the on exit event of main window
I can't remember the exact event name.
if u write that event u can stop closing the window
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34867969
In program.cs, pass your own implementation of ApplicationContext that only shuts down the app when all forms are closed:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyContext());
        }
    }
 
    public class MyContext : ApplicationContext
    {
        public MyContext()
        {
            Application.Idle += new EventHandler(Application_Idle);
            MainForm mf = new MainForm();
            mf.Show();
        }
 
        void Application_Idle(object sender, EventArgs e)
        {
            if (Application.OpenForms.Count == 0)
                Application.Exit();
        }
 
    }
 
}

Open in new window


Now you can Show() the second form BEFORE you Close() the main form and the app will stay open:
// in MainForm:
Form2 f2 = new Form2();
f2.Show();
this.Close();

Open in new window


The app will close automatically when the LAST open form is closed...
0
 
LVL 2

Expert Comment

by:pchui
ID: 34868126
Use Form.Show() instead of Application.Run() to start your main window. Wait for your program to finish and call Application.DoEvents() to keep the messages pumping.

using System;
using System.Windows.Forms;

namespace TwoWindows
{
    static class Program
    {
        public static Form1 form1;
        public static Form2 form2;

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

            Program.form1 = new Form1();
            Program.form1.Show();

            while (Application.OpenForms.Count > 0)
                Application.DoEvents();
        }
    }
}

Open in new window


Make sure you don't have any lifetime issues with the second window getting destroyed when the first window closes. You can declare the Forms global somewhere as I have done in the main Program class.

You code to create the second window looks like this

            Program.form2 = new Form2();
            Program.form2.Show();

Open in new window


0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34868176
@pchui....except that RAMPS CPU usage up because of your TIGHT loop.  The ApplicationContext does the same thing without monopolizing the processor time...
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 2

Expert Comment

by:pchui
ID: 34868299
@Idle_Mind... you are correct. My code needs some to break up the tight loop

while (Application.OpenForms.Count > 0)
{
    System.Threading.Thread.Sleep(100);
    Application.DoEvents();
}

Open in new window


Brings the CPU usage to 0% while idle on my system
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34868313
I still wouldn't do it that way but technically it works...
0
 
LVL 6

Assisted Solution

by:rajeshjamnadas
rajeshjamnadas earned 100 total points
ID: 34868582
try this logic

i hv created button1 and on click of that following code.
this logic will work for u

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

            private void showf()
            {
                  Application.Run(new Form1());
            }
0
 
LVL 5

Expert Comment

by:ennixo
ID: 34868976
Loops are bad !

I think the best solution is to create your own ApplicationContext, just as Idle_Mind said.
0
 
LVL 11

Expert Comment

by:SAMIR BHOGAYTA
ID: 34870536
Hi, you have to use this code


for(int k = 0;k < Application.OpenFormsk].Count;k++)
{
           Application.OpenForms[k].Close();
}
0
 
LVL 11

Expert Comment

by:SAMIR BHOGAYTA
ID: 34870541
hi, You have to write this code on MainForm_Closing() Event. ok
0
 

Author Comment

by:jtran007
ID: 34878660
Hi,

I have a scenario like this: I have 4 windows statically created durin the design time.
And they are dynamically shown as the process is going on.

First: win1 is shown to display instruction, then user click button 1 to go to win2 (win1 is closed now or later: my question )
Second: win2 display progress bar showing the initializastion, when done the program , win2 is closed,
             and program display (show()) win3.
Third: win3 start collecting data, when done, win3 is close, and program display win 4
Fourth: win 4 display completion, and user click close, program exits.

From this scenario, which technique is the best one.

Thanks for your sharing knowlege with me.

JT
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 400 total points
ID: 34878972
The ApplicationContext approach back here will handle that just fine:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_26813822.html#34867969
0
 

Author Closing Comment

by:jtran007
ID: 34896246
Thanks,
JT
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now