I am coding a simple sidescroller in C# using Windows Form Applications. I want it so when the player touches an exit point, this immediately loads a new level.
To implement this, I use the following code:
if (player.Bounds.IntersectsWith(exit.Bounds))
{
Form2 myNewForm = new Form2();
myNewForm.Visible = true;
this.Hide();
}
This works. However, it loads numerous instances of form2 - I only want it to load once. I don't know how to write this (sorry, I'm a newbie - it took me a while just to write this code!).
Also, loading a level via a new form is inefficient. Is there a way to unload the open form to load the next one in the same window/instance, rather than creating another separate window?
Sorry if this is unclear. I've done my best research + I'm new. Please don't mention XNA! Thanks.
You need a small modification to your project's Program.cs file to change the way your app decides to terminate. You simple exit when there no more windows left. Make it look like this:
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var start = new Form1();
start.FormClosed += WindowClosed;
start.Show();
Application.Run();
}
static void WindowClosed(object sender, FormClosedEventArgs e) {
if (Application.OpenForms.Count == 0) Application.Exit();
else Application.OpenForms[0].FormClosed += WindowClosed;
}
}
Now it is simple:
if (player.Bounds.IntersectsWith(exit.Bounds))
{
new Form2().Show();
this.Close();
}
You can use Application.OpenForms[] collection to retrieve the Opened form instance and then Show it.
Try This:
Form2 frmMyForm = (Form2)Application.OpenForms["formName"];
frmMyForm.Show();
The actual problem is not in your form being loaded multiple times, but in your game logic not being suspended when the end of the level is reached. It means that your game keeps playing an old level when a new level is already loaded.
If Form1 is the main form then your whole application will shutdown. You need bootstraper which will be the entry point of your application, not the Form1. If you do that your Form1 will be a child in the same sense as will be Form2. You can open and close them without shutting down the application. If you don't know how to do that, just create another empty form, let's call it Main and make it the starting form of your application. Then hide it and open Form1 from Main form as Modal. Then when you complete level in Form1, close Form1, the code flow will return to Main form and you'll spawn Form2 from Main form as Modal. You'll have fully predictable logic, where all forms are opened from a single controlled place.
Related
I have some code meant to open a new windows form when one is closed, and yet I get nothing, no error.
I've tried a few different methods for opening a new form on a Form.FormClosed event.
This is the code I have right now:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Form1 myForm = new Form1();
myForm.Show();
}
But yet I get no error, nothing.
I'm expecting for a new windows form to be opened when I close another one.
Any help would be appreciated, thanks!
The problem is that as soon as the first Form1 instance closes, your application shuts down and exits because the application message loop is defined with the initial Form instance, and it is just waiting for events on that form until it closes. On closing, the application will exit, opening a new form doesn't stop this process.
You need to adjust the Main() method in Program.cs to look something like this:
[STAThread]
static void Main()
{
// ... Application configuration as required here
new Form1().Show(); // The first form instance is now no longer bound to the Application message loop. Start it before we begin the run loop
Application.Run(); // Don't pass in Form1
}
Your original code should now work. I might add however, this is not a great user experience. Carefully consider what you're trying to achieve, and perhaps consider alternatives - do you just need a "reset form" button? Or is the primary goal to prevent a user from closing the application? If the latter, you can remove the Close icon altogether.
Perhaps something simple to get your going forward.
private Form1 myForm = new Form1(); //Declare the form as a private member variable
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
e.Cancel = true; //Cancel the closing so this object stays alive
this.Visible = false; //Hide this form
myForm.Show(); //Show the next form
}
Please note #pcdevs comment. You'll need a way to indicate the form is being closed/application quiting vs progressing to the next step/form. You might want to look at some CodeProject articles about "C# Winform Wizards", those sequential dialog prompt apps...
I'm Trying to develop an app for an old handheld device running .Net 3.5 Win CE 5 however I cannot seem to get over a basic hurdle switching forms!!
I started using
Application.Run(new frm_class());
but this started crashing after opening any more then 2 forms.
I then tried.
this.hide();
frm_class frm = new frm_class();
frm.show();
then just ended up being a constant loop of loading the form
then I seen someone wrote a very simple class to handle this.
public static void switchForm(Form newForm, Form oldform)
{
newForm.Show();
oldform.Hide();
oldform.Dispose();
}
call via
frm_class frm = new frm_class();
switchform(frm,this);
which shuts the app down when loading the second form.
This seems so stupid but I cannot find out a way of just navigating through simple forms ie close this form then open this one or vice versa!!
can anyone help?
Application.Run(new frm_class()); will start a message loop and makes the specified form visible and waits untill it is closed. Once the specified form closes, the message loop terminates.
oldform.Dispose(); will dispose (and close) the form, not hide it.
Your second solution seems like the one you should take, which shouldn't loop. Make sure the code isn't in the constructor or form_load event if you're creating the same form again. Can you post the code surrounding this?
You could also remove the new frm_class() argument from Application.Run(). Which will create a constant running message loop. Just don't forget to call Application.Exit() at some point.
You should make sure the form is made visible before the parameterless Application.Run() because the execution inside this codeblock wont continue untill Application.Exit() is called from inside your form.
frm_class frm = new frm_class();
frm.Show();
Application.Run();
// Some button or event inside the form should be executing the exit call:
Application.Exit();
Please refer to the diagram below:
I'm looking for the best way from one form to open another form. Once the menu form is open, I want to close the login form. I have tried to do this, but I got lost when I try to call it as a child of the MDI container.
The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.
The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:
static void Main()
{
LoginForm fLogin = new LoginForm();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
else
{
Application.Exit();
}
}
if you develop WPF form, you can use 'http://wpfmdi.codeplex.com/'. or in Win Form you could play with form such that you want
try this
//global form
LoginForm login = new LoginForm();
public void menuOpen()
{
if(login.Visible)
login.Close();
}
how to open form 1 on close button click X in form 2
i tried this but it is not working:
private void supplierShow_FormClosing(object sender, EventArgs e)
{
new suppliersList().Show();
}
Thank you.
Not fully sure without knowing more your code but to me it looks like you are declaring a local variable (new suppliersList of base class Form probably) and showing the form from the Closing event of another form.
Your Form2 object is probably going to be deleted/disposed/garbage collected soon and at that point I am not completely sure that the form declared within that scope would still have a nice life.
If Form2 is the application form, the application will actually terminate when you close it.
in general I think that this kind of form switching is best done and controlled from the main method, the same place where you probably have Application.Run(new Form2()); because in there you have full control of the application flow and MessageLoops...
I have to solutions:
First:
You may have a unique reference to your suppliersList in Program class:
public static suppliersList SuppList = new suppliersList();
you can now hide it if you want:
Program.SuppList.Hide();
you can show it anytime, too:
Program.SuppList.Show();
Be carefull! Don't Dispose SuppList. If you did, assign to it a new object new suppliersList();. Please note that this solution would success only if form1 is not the main form (i.e. Application.Run(new form1()); )
Second:
You can start form2 as a child of window of form1:
new suppliersList().Show(this);
because, as in the other answer, the application loops are on form1. If form1 is closed, then entire application will be closed too. However, starting a child window of the main window will prevent application close.
If the answer is useful for you, please mark it as your best answer.
I have 2 forms ...when i start the application..and use the close "X" from the title bar the entire application closes...now when i select an option from the 1st form in my case it is a button "ADD" as its a phonebook application..it goes to the 2nd form as i have used 1stform.hide() and 2ndform.show()...now when i do "X" from the title bar it doesnt shutdown completely as the 1stform is not closed....how to program it in such a way tht any stage the entire application should close
Your first form is set as the startup form. That means whenever it gets closed, your entire application is closed. And conversely, your application does not close until it gets closed. So when you hide the startup form and show the second form, the user closing the second form does not trigger your application closing because they have only closed a secondary, non-modal dialog.
I recommend changing your design so that the startup form is also the main form of your application. No sense trying to work around built-in functionality that can actually be useful. You want the application to quit when the main form is closed, no matter what other child forms are opened.
But the quick-and-dirty solution in your case is to make a call to Application.Exit. That will close all of the currently open forms and quit your application immediately. As I said just above, I don't so much recommend this approach because having to call Application.Exit from every form's FormClosed event handler is a sign that something has gone seriously wrong in your design.
If the single startup form paradigm doesn't work out for you, you should look into taking matters into your own hands and customizing the Main method in your Program.cs source file. See the answers given to this related question for some ideas on how that might work for you.
What you can do is to use the Form's FormClosing event, and add the following code:
Application.Exit();
This will stop the entire application, and close all windows. However, if a background thread is running, the process itself will survive. In this case you can use:
Environment.Exit();
Add a Application.Exit on every forms's Closing event
like this:
Create an closing event handler first
private void Form_ClosingEventhandler()(object sender, CancelEventArgs e)
{
//Perform any processing if required like saving user settings or cleaning resources
Application.Exit();
}
then bind this event to any form you create.
//Where you create new form and show it.
Form1 frm= new Form1();
//set other properties
frm.Closing += new EventHandler(Form_ClosingEventhandler);
Form2 frm2= new Form2();
//set other properties
frm2.Closing += new EventHandler(Form_ClosingEventhandler);
Surely you don't want to shut down the entire application after the user adds a phone number? You just need to make sure that your main window becomes visible again. Write that like this:
private void AddButton_Click(object sender, EventArgs e) {
var frm = new AddPhoneNumber();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = this.Location;
frm.Size = this.Size; // optional
frm.FormClosing += delegate { this.Show(); };
frm.Show();
this.Hide();
}