How to show multiple forms simultaneously - c#

I know this may have been answered, but I just can't find a suitable answer. Any idea how to show more than one Windows Form?
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
Application.Run(new MenuModule());
}
By declaring two Application.Run, the the Windows Form will show after I exit the first.

When you use that overload of Application.Run it will block until the form you passed has closed.
You could try:
new Main().Show();
new MenuModule().Show();
Application.Run();
This will run until you call Application.Exit even if both forms have been closed. So a better option might be:
new MenuModule().Show();
Application.Run( new Main() );
Which will cause the application to exit after the Main form has closed, regardless of the status of the MenuModule form.
As an option you could also have the Main form show the second one, that'll work too.

you can create an object in 'Main' class (form) contractor.
public main(){
.
.
.
new MenuModule().show();
.
.
.
}

Related

Visual studio does not show UI while running app

I have been working on c# for about 3 hours and Visual Studio does not show the UI while running the application. It shows the UI in designer but after compiling and running, it just goes blank.
Two things to test:
In the code file Program.cs, you will find something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Does the name of the form in the line Application.Run match the name of your form?
Your form's code behind (Form1.cs) should have a constructor looking like this
public Form1() // Where the name of the constructor must match the one of the form class.
{
InitializeComponent();
// Your code goes here (if any) ...
}
Does it have this constructor? If yes, does it call InitializeComponent?
InitializeComponent is very important, because it creates the controls and configures the form. You may have replaced it with your own code. Always call it before your initialization code.
I guess the entry point if your application is wrong. Check the solution properties (right click on your application/solution in the solution explorer -> properties ) for the correct entry point.
It looks like you have more than one form.
Go to the Program.cs file and verify if the class of the form is in Application.Run() method
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main ()
{
Application.EnableVisualStyles ();
Application.SetCompatibleTextRenderingDefault (false);
Application.Run (new urltetx());
}
}

Fully closing application in C# just won't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm writing a simple game and I have a function that basically should just exit the application or rather close everything currently open in C# (I'm using Windows Forms).
private void ExitApp()
{
Application.Exit();
}
However, nothing will work. I have tried using Environment.Exit(0), Application.Exit, tried using a for loop to close every form but it just won't work. What I have noticed is that even if I press the X button, the solution won't close, but something seems to be running in the background and I do not know what. Browsed Stackoverflow forum for similar issues, browsed other forums, googled for days, but nothing seemed to help.
This is the code for opening more forms :
Podešavanja p = new Podešavanja();
private void Settings_FormClosing(object sender, FormClosingEventArgs e)
{
this.Close();
Menu m = new Menu();
m.Show();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
Menu m = new Menu();
m.Show();
}
The SettingsFormClosing event actually just opens up a new Form for me, without closing the previous one, why, I do not know.
Any help would be greatly appreciated.
The problem is that your forms are all running on the same thread. Take a look at your Program.cs file. See how it calls Application.Run(New Form1())? This is where your application form initially runs on the application thread.
So the problem we have here is: you are trying to close your Form, which is hosting your second form. Suppose your a single form with a button control on it. Now suppose you tried to tell your application you wanted the window form to close, but wanted the button to stay active and open -- crazy right? Well what you are trying to do is essentially the same thing -- mind you I am basing this on the assumption you are not multithreading. Your Form1 is hosting your Form2 instance, and thus you cannot run Form2 if Form1 is disposed. The best way I can think of, at least off the top of my head, is you need to create a recursive call in your Program.cs and tell it whether or not it needs to run a new Form before it truly exits. This is questionable at best, but it might suffice.
So let's modify our Program.cs Then:
static class Program
{
//This is where we set the current form running -- or to be run.
static Form CurrentForm;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Obviously, Form 1 starts everything so we hardcode that here on startup.
CurrentForm = new Form1();
//Then call our Run method we created, which starts the cycle.
Run();
}
//This runs the current form
static void Run()
{
//Tell our program to run this current form on the application thread
Application.Run(CurrentForm);
//Once the form OFFICIALLY closes it will execute the code below
//Until that point, imagine Application.Run being stuck there
if(CurrentForm != null && CurrentForm.IsDisposed == false)
{
//If our current form is NOT null and it is NOT disposed,
//Then that means the application has a new form to display
//So we will recall this method.
Run();
}
}
//This method is what we will call inside our forms when we want to
//close the window and open a new one.
public static void StartNew(Form form)
{
//Close the current form running
CurrentForm.Close();
//Set the new form to be run
CurrentForm = form;
//Once all this is called, imagine the program now
//Releasing Application.Run and executing the code after
}
}
Okay so if you wrap your head around this, then closing and opening a new form is a piece of cake. We simply can open new forms on button click events.
Inside Form1.cs:
private void OpenForm2_Click(object sender, EventArgs e)
{
Program.StartNew(new Form2());
}
Inside Form2.cs
private void OpenForm1_Click(object sender, EventArgs e)
{
Program.StartNew(new Form1());
}
I will reiterate, this method is super questionable.... But it may suffice for what ever you are doing. It is also super reusable through your application regardless of the class or form.

Methods this.hide() vs this.close()

My c# windows forms application has 5 forms which I am displaying one after the another. When the user clicks on next button, the code I have given is:
new Form1().Show();
this.Hide();
However I do not want my current Form to hide. I want to close it/dispose it so that it does not consume memory. I want to release its resources like the images and variable used as soon as I am done with it.
For that I tried implementing:
new Form1().Show();
this.Close(); //Form 2
but this simply closes both the forms.
I even tried swapping the positions of the above two lines:
this.Close();
new Form1().Show();
but this also does same thing.
How do I release the resources of one form as soon as I am done with it? because my program throws out of memory exception when I try to re-open my Form 2 using:
new Form2().Show();
this.Hide();
You can start your NewForm in a new thread and create a new message loop
When the main message loop is closed, the application exits. In Windows Forms, this loop is closed when the Exit method is called
For more information see here.
var th = new Thread(() => Application.Run(new NewForm()));
th.SetApartmentState(ApartmentState.STA); // Deprecation Fix
th.Start();
this.Close();
Another way to do it, is to manage the application context yourself. Here is a small demo:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var myApplicationContext = new MyApplicationContext(new Form1()))
{
Application.Run(myApplicationContext);
}
}
You can define your tailored made ApplicationContext in the following way:
public class MyApplicationContext : ApplicationContext
{
public MyApplicationContext(Form mainForm)
:base(mainForm)
{
}
protected override void OnMainFormClosed(object sender, EventArgs e)
{
if (Form.ActiveForm != null)
{
this.MainForm = Form.ActiveForm;
}
else
{
base.OnMainFormClosed(sender, e);
}
}
}
And now, you could do the following on the Button.Click event handler:
var f = new Form();
f.Show();
this.Close();
And the application will keep on running. Basically this way you keep the app alive while there is at least one active form.
NOTE Haven't tested it but it should work.
Closing the form which the Program start in its main function will close the application, an idea is to have a parent Form and make it the main form, and never close it, this can be a hidden form if you want.
I am not working with Windows forms since long time ago but found on this page the reason behind behavior you are getting:
http://msdn.microsoft.com/en-us/library/ms157902(v=vs.110).aspx
Typically, the main function of an application calls this method and
passes to it the main window of the application. This method adds an
event handler to the mainForm parameter for the Closed event. The
event handler calls ExitThread to clean up the application.
Also on this question How do I prevent the app from terminating when I close the startup form? there was a discussion about something the same
I am not sure if it would work for you. But when I had the same problem while dealing with a login form... i just used ShowDialog() instead of Show() , (and for me it solved the problem ) Just Like:
this.Hide();
MainForm MForm = new MainForm();
MForm.ShowDialog();
this.Close();
By default, a C# Forms application creates a "root" form in the Program.Main() method and passes that to the Application.Run() method. When this Form is closed, your program will exit.
However, you can change this behavior by using a different Application.Run() overload. Just don't pass the Form instance to Run(). Instead, show the form before calling Application.Run(), and then later on (when you finally do want the program to quit) use the Application.ExitThread() method to tell the Application class you're ready to close the application.

How to exit a Windows Forms/C# program

Class A has a Form1 (subclass of System.Windows.Forms.Form) member.
class A {
Form1 form;
public A()
{
form = new Form1();
form.Show();
}
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
A a = new A();
Application.Run();
}
The problem is I do not know how to exit the program. I have tried Application.Exit() when handling the Form.Closed event or call A.Dispose(), but the Windows Task Manager still lists the process of my program.
How do I finish this program?
Application.Run has 3 overloads. You are using this one with no arguments.
Windows runs your program in a message loop, but it doesn't care about your form.
So if you close your form it doesn't matter; the program will still run.
The second overload is what everyone uses, Application.Run(Form). This one runs a Windows message loop over your form, so when you click close on the window, the application closes.
Your code should be:
class A {
Form1 form;
public A()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form = new Form1();
form.Show();
Application.Run(form);
}
}
[STAThread]
static void Main()
{
A a = new A();
}
Following Microsoft you should use this:
Application.Run(a.Form);
Because MSDN states that
Most Windows Forms developers will not need to use this version of the method. You should use the Run(Form) overload to start an application with a main form, so that the application terminates when the main form is closed.
I think you have a mixup there. Check the documentation for Application.Exit.
There you will see that Exit will raise the Closed event for you, and calling Exit there might cause an infinite loop (which might be causing your problem, that the application is still visible).
Try this:
Environment.Exit(1);

Can I close the program from the Main constructor?

Can you exit an application before the constructor is finished and the main form is loaded?
At startup, I have a loading screen that displays before the main form is loaded. The loading screen is displayed from the constructor before the constructor has finished.
I do something similar with an exit screen by using a variable between the main form and the exit screen. I have an application exit in the main form if the exit screen returns true.
Finally, should all the thread/class/loading/program setup be done in the main constructor or am I doing it wrong?
Update:
I mean after the program.cs and in the static main
namespace app
{
public partial class app1 : Form
{
public app1()
{
InitializeComponent();
// open loading screen
// initialize vars
// create objects
}
// form opens when app1() finishes
Is app1() the right place to initialize everything?
If I try to send a "close" message back from the loading screen before app1() is finished, it doesn't work - the process still runs even though nothing is open.
I've found that if I try to kill my application from the main form constructor when I still have the splash screen showing on a different thread (which looks similar to what you are doing), that Application.Exit() does not work, but Environment.Exit(-1) does.
try this,
public partial class MyForm : Form
{
public MyForm()
{
if (MyFunc())
{
this.Shown += new EventHandler(MyForm_CloseOnStart);
}
}
private void MyForm_CloseOnStart(object sender, EventArgs e)
{
this.Close();
}
}
it will work well...
Which main constructor of which class?
Are you talking about the static method Main that has a default location in the Program class?
You use that method to do initialization that needs to occur before you open any windows on screen.
Obviously, if you need to use a loading screen, you will probably want to move some code somewhere else, as you need a message loop around forms, and the message loop will block until your form closes.
If you return from the Main method before you open any form, then no form will be shown obviously.
Having said all that, I feel your question is a bit vague and I'm pretty sure I didn't understand exactly what it is that you're asking.
First and foremost, Main is not a constructor, it's just a static method.
When main thread ends:
background threads are "killed/abandoned"
foreground threads (the default when creating threads) are waited till they finish.
you can break constructor only via throwing an exception. To do that surreptitiously, throw you own specific exception.
class ConstructorAbortedException : Exception { }
class Foo
{
public Foo()
{
if(goesWrong)
{
throw new ConstructorAbortedException();
}
}
}
void Bar()
{
try
{
Foo f = new Foo();
}
catch(ConstructorAbortedException)
{
//..
}
}
As jontsnz answered, the code with
Environment.Exit(-1)
works fine in the constructor, but this causes the application to throw an "Application Hang" event, which can be seen as an error in the Windows Event Viewer. Using
Environment.Exit(0)
exits without registering an error though, so I prefer that one.

Categories

Resources