I have two forms in my c# windows project . The first form is called is called "loginform" and the other one is called "mainform" . I want to move to the mainform on button click But when i reached at the mainform , the problem is when i tries to close my second form which is named "mainform" here , the application does not close and i have to use the visual studio to terminate the project. below is the code for moving to second form
this.Hide();
mainform mf = new mainform();
mf.Show();
I found the answer. On the second form add the following code on the formclosed event .
private void mainform_FormClosed(object sender, FormClosedEventArgs e)
{
Application.ExitThread();
}
The problem you have is because “your code” basically “throws away” ANY reference back to this when the code sets it as “hidden”…
this.Hide();
After this line of code is executed, mainform is created and shown…
mainform mf = new mainform();
mf.Show();
Assuming, there is no code “after” the code above… then basically this has now been lost. The user can NOT see the form nor interact with it. mainform is shown… but it knows nothing about this. this is now lost and you have NO way of getting it back. That’s why it keeps running.
Obviously, mainform has no idea about this i.e. … the form that “created” it, however it DOES need this to stay alive. IF we “close” this and this created mainform… then mainform depends on this and will also close when this closes.
mainform mf = new mainform();
mf.Show();
this.Close();
Then, mainform gets killed as soon a this closes. So that will not work. However… if you changed the Show to ShowDialog… for the mf.ShowDialog(), then it would work and this would get closed properly.
Therefore, IF you want to “CLOSE” the form that “created” another form, then you should spin off another process for the mainform or pass this to the mainform and let it close it when it is done. I am sure there are other ways to do this and if Application.ExitThread(); ... works for you then go for it.
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 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.
What i want to do:
->Open a MDI form
->Close the projects main form
->Without closing the application
What i have done:
frmMain fm = new frmMain();
fm.Show();
this.Close()
Any help would be appreciated! :)
If you actually wish to close the main form, but leave the application running, you can make your default class launch the application context:
using(MyContext myContext = new MyContext())
{
Applicaton.Run(myContext);
}
where MyContext inherits from ApplicatonContext.
Your application context can then load and close forms as needed. I do this with one project where I have the context launch a login form. Only after it is completed successfully does the main form get loaded. I also allow the "logging out" from the program to be handled by terminating the main form and reloading the login form.
EDIT: From the comments, it may be that all you are looking for is .Hide(). This doesn't cause your form to unload and a call to .Show() will restore it (for example, you can use a timer or another form holding a reference to your main form to make the call). I prefer to use an ApplicationContext because it takes the responsibility for keeping your program in memory away from a UI element which the user may attempt to close.
You can use the Hide method.
Try doing this:
frmMain fm = new frmMain();
this.Hide();
fm.Show();
Or:
frmMain fm = new frmMain();
this.Hide();
fm.ShowDialog();
this.Show();
The latter will open the window, and once it is closed, the previous window will reappear.
What I did to get around this is:
this.Hide()
Probably not the best way to do this, but still.
You could even get it back by calling
this.Show()
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();
}