Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

windows forms closing and loading using c#

Posted on 2009-12-29
14
Medium Priority
?
2,743 Views
Last Modified: 2013-11-12
i used to to develop windows programs using vb6 where loading and unloading forms was simple:

unload me
form1.show

however, in C# (.net 3.5 visual studio 2008) its a little more tricky

this is what i have used:

            Main main = new Main();
            main.Show();
            this.Hide();

it runs fine but instead of hiding the first form, i want to unload it altogether ... not even keep it in the memory

please guide
0
Comment
Question by:RakeshBhandari
  • 5
  • 3
  • 2
  • +3
14 Comments
 
LVL 5

Expert Comment

by:zzx999
ID: 26136961
use Dispose() method.
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 26136992
unfortunately, if u unload/dispose 'this', the main form is also being unloaded.
i assume 'this' is the initial form which create and display the Main form.
the only way to achieve this is by running the initial form ('this') from non-gui console while make it hidden.
what i mean is that console app will create the initial form ('this'), when it comes to the point u wish to display the Main form, this is unloaded and main form is create and displayed:

for the code snippet i'll use InitialForm and 'this' in your code.

console code:
static void Main(){
InitialForm f = new InitialForm();
f.ShowDialog();

//here the InitialForm instance is already disposed since the form was closed when back from ShowDialog.

Main main = new Main();
main.Show();
}

unless initial form consumes great deal of memory, i'd choose this option but use Hide() instead.



0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 26137009
using this.Dispose() won't do any good.
it will cause your 'this' form to unload the main form and itself as well and the app will exit.

btw, the only missing part in my example is the code that hides the console app so the user won't see it.
if u wish to use this approach i'll post u a console app code which implements that.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 26137054
there's an alternative which is fooling the visual studio to think that your project is windows application, while in fact u create your initial form from the static Main.
in this case u don't have to worry about hiding the console app (it won't be shown).

to achieve this, create a Console App project and add your forms to the project.
in Static void Main(), create your initial form and once it's back from ShowDialog u can explicitly dispose it and display your Main form:

 class Program
    {
        static void Main(string[] args)
        {
 InitialForm f1 = new InitialForm();
            f1.ShowDialog();
            f1.Dispose();

            MainForm f2 = new MainForm();
            f2.ShowDialog();
}
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 1332 total points
ID: 26137463
Everything in .Net is a class, which you should be familiar with from VB6.  Just like in VB6 you declare varaiables to hold an instance of a particular class, then you create a new instance of that class, then you can use the methods & properties of that class, then you can set that class = Nothing to release.

'Declare variable
Dim o As MyClass
'Create new instance
Set o = New MyClass
'Use it
o.SomeMethod
'Release it
Set o = Nothing


The same concept is basically true in .Net.  Some objects have a method "Dispose" which explicitly tells them to release their resources. The .Net also has what's called a garbage collector - it finds things that are no longer being used and automatically frees their memory.
// Declare variable
MyClass o;
// Create new instance
o = new MyClass();
// Use it
o.SomeMethod();
// Release it (if the class supports  it, call the .Dispose method instead of just setting null)
o.Dispose();
o = null;

// Suppose you have a button on Form1 which opens form 2
// The frmSecondForm variable will only live as long as this
// method (because it's locally scoped, i.e. declared in this method),
// so as soon as the form is closed it will be 
// queued for garbage collection
protected void Button1_Click(object sender, EventArgs e)
{
    Form2 frmSecondForm = new Form2();
    frmSecondForm.Show();
}


// Then in form 2 if you have another button that closes the form
protected void ButtonClose_Click(object sender, EventArgs e)
{
    this.Close();
}

Open in new window

0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 26137590
...also,

Form.Close(); closes the form and Form.Hide(); simply hides it from the user.  If you open a form with a text box on it, type some stuff in the textbox, .Hide() the form and then .Show() the form your text is still there. If you .Close() it and then .Show() it the textbox is empty, you're starting over.

The memory used to hold the form's class is released when the Garbage Collector sees that the variable the form class was assigned to is no longer in use.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26138196
You can write your own ApplicationContext which only shuts down when ALL forms have been closed:
(this allows you to CLOSE the first form without worrying about the app shutting down on you)
using System;
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);
            Form1 f1 = new Form1();
            f1.Show();
        }
 
        void Application_Idle(object sender, EventArgs e)
        {
            if (Application.OpenForms.Count == 0)
                Application.Exit();
        }
 
    }
 
}

Open in new window

0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 26138236
Short answer is you want this.Close instead of this.Hide. ;)

Let us know if that gives you any trouble.

Main main = new Main();
main.Show();
this.Close();


0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 26138257
Except that as the others pointed out, if that form was the "startup form" then your app would also close (along with any still open forms).

sedgwick is keeping the app alive by using ShowDialog() instead of Application.Run().
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 26138345
@Idle_Mind

Saw that, but the question is "instead of hiding the first form, i want to unload it altogether ... not even keep it in the memory", and I just wanted to clarify my earlier pre-coffee ramblings. ;)

Just rather him try changing this.Hide to this.Close and report back any unintended consequences to avoid a potentially confusing discussion of application contexts et al if it's not necessary.
0
 
LVL 2

Author Comment

by:RakeshBhandari
ID: 26143623
this.close()  closes the entire application instead of just closing the first form


doing this in vb6 was so much more simpler

even .dispose() closes the entire application

i thank all those who have contributed to the solution... but i'm more confused now
0
 
LVL 1

Assisted Solution

by:Jalaly
Jalaly earned 668 total points
ID: 26144939
It seems that you want to close first form and start another one. am I right?
For doing so best way is changing the Main method in Program class. In Visual Studio 2008 change the Main method attached code. Application.Run(new Form1()) wait till you close the form and after that you can simply call second form. Note that in this case first form is closed and cleaned from memory.
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());
//form1 is closed. now show second form
            Application.Run(new Form2());
        }
    }

Open in new window

0
 
LVL 33

Assisted Solution

by:Todd Gerbert
Todd Gerbert earned 1332 total points
ID: 26145110
RakeshBhandari,

In your project you should have a Program.cs with a Main() function in it, which serves the same purpose as a Sub Main in VB6.

The line that reads Application.Run(new Form1()) basically says "show form 1 and wait until it's closed"  Form1 is shown and your program goes about it's business.  As soon as Form1 is closed the Main() function simply continues to the next line, which is probably nothing in your case, just the end of Main(), and when Main() finishes your program ends.

Idle_Mind's solution above makes Application.Run() wait for EVERY form to close, that way you can just show Form2 before closing Form1 and your program will continue to run - I would probably go that route if I were you.

If the first form is a "splash" screen and you only have one other form you can show the first form in Program.cs, in Main(), before the Application.Run line, and change Application.Run() to use the second form as the "main" form. e.g.,
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    // This line will wait until Form1 is closed before continuing, so the user
    // must close the form by clicking a button, for example, or you can
    // use a timer and have the form close itself.    
    new Form1.ShowDialog();

    // Now the splash screen is gone, run the program with
    // form2 as the "main" form
    Application.Run(new Form2());
}



You can also have your program continue to run whether there are any open forms or not by using Application.Run() without any parameters.  That will make your Main() wait until you specifically tell the program to end using Application.Exit(). The up-side is you can show and hide any forms you want without the program ending, down-side is you have to make absolutely certain you call Application.Exit() somewhere in your code (since you can't just rely on a form closing) otherwise the program will never end.

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

    // Show Form1
    new Form1.Show();

    // Will cause program to continue running until Application.Exit() is called
    // somewhere else in your code.
    Application.Run();
}
0
 
LVL 2

Author Closing Comment

by:RakeshBhandari
ID: 31670710
thank you!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…

577 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