How can I close the MainForm, without closing the others? - c#

So, I'm writing a Hangman, and at the MainForm you have to choose if you want to play single player or multiplayer. When I choose which one I want, this MainForm should close( I use this.Close() ) and trigger another Form, but instead the entire program shuts down.
private void button2_Click(object sender, EventArgs e)
{
Form f2 = new Form1();
f2.Show();
this.Close();
}
If in Programs.cs I modify the code like this:
Form f4 = new Form4();
f4.Show();
Application.Run();
everything goes well, but If I won't exit the program using Application.Exit(), it will still run in the background.
So, how could I solve this problem?

You can't close the parent form and keep the children alive.
Use this.Hide() instead of this.Close()
Then on the Form2_FormClosed Event you can do Application.Exit()
or you can even show the MainForm Again.
OR:
Form2 f2 = new Form2();
this.Visible = false;
f2.ShowDialog();
this.Close();

If you want a basic form that will pretty much just allow the user to play until they close the other form then close this form, use this:
private void button2_Click(object sender, EventArgs e)
{
Form f2 = new Form1();
this.Hide();
f2.ShowDialog();
this.Close();
}
or something a bit more fancy will allow you to close the form if the user selects something like not wanting to play another game or change difficulty settings or whatever. You can do that like this:
private void button2_Click(object sender, EventArgs e)
{
Form f2 = new Form1();
this.Hide();
if(f2.ShowDialog() == DialogResult.OK)
{
this.Show();
}
else
{
this.Close();
}
}

You can show (dialog) your form before Application.Run(new MainForm()), so you don't need to close the Mainform

Related

Form remains open in the background after closing it

So I want to show a form and close the other form so I did this in form1:
private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 x = new Form2();
x.Show();
this.Hide();
//didn't use this.close() cause then the whole program will close instead of
//just the current form
}
Then I wanted the main form to open again after the 2nd form is closed so I did this in form2:
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Form1 x = new Form1();
x.Show();
}
Now the problem is when I'm back in the main form after closing the 2nd form. if I close the main form it doesn't fully close and still remains open in the background (I found it in task manager). I think its because the "show" method just opens another form instead of making the form appear so the main form which got hidden is still there running in the background.
what should I do to make the form get closed when I exit it?
I tried putting this.close(); in the form closed and form closing event but both resulted in a crash.
When you write:
Form1 x = new Form1();
you are creating a new Form1 object, so x refers to the new one and not to the original one. Instead, you could use this:
private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var form2 = new Form2())
{
this.Hide();
form2.ShowDialog();
}
this.Show();
}
When ShowDialog() is called, the code following it is not executed until after the dialog box is closed, so this.Show() will execute only after Form2 is closed.
Another option is to simply subscribe to the FormClosed() event of Form2 when you create it, then un-hide your instance of Form1 from there:
// ... all in Form1 ...
private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
Form2 x = new Form2();
x.FormClosed += X_FormClosed;
x.Show();
}
private void X_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
So then when you close Form2 your instance of Form1 will automatically re-appear.

How to Focus to another form in C#

I have a program which opens two forms
and I want when I click on Form1
then Focus on Form2.
private void Form1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Focus();
}
But this doesn't work, what's wrong in my code?
EDIT:
I found already answered Here by #moguzalp at the comments
First of all that Form2 is never visible.
private void Form1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
frm2.Focus();
}
If that Form is visible though with your code, that means you need to get same reference and call Focus() against it.
EDIT:
Then you need to have a reference to that Form.
At some point you created that Form and assigned it to a vairable/field or anything like that.
You need to call Focus or Activate against it.
Example:
Inside Form1 when you create a Form2 instance:
public class Form1 : Form
{
private Form _frm2;
//That code you probably have somewhere. You need to make sure that this Form instance is accessible inside the handler to use it.
public void Stuff() {
_frm2 = new Form2();
_frm2.Show();
}
private void Form1_Click(object sender, EventArgs e)
{
_frm2.Focus(); //or _frm2.Activate();
}
}
If you can have a form opened, try finding it:
using System.Linq;
...
// Do we have any Form2 instances opened?
Form2 frm2 = Application
.OpenForms
.OfType<Form2>()
.LastOrDefault(); // <- If we have many Form2 instances, let's take the last one
// ...No. We have to create and show Form2 instance
if (null == frm2) {
frm2 = new Form2();
frm2.Show();
}
else { // ...Yes. We have to activate it (i.e. bring to front, restore if minimized, focus)
frm2.Activate();
}
If you want to Show your frm2, you should call frm2.Show(); or frm2.ShowDialog();.
Also, before 'Show' call you can set frm2.TopMost = true; if you want this form to be on the top.
So it could be:
private void Form1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.TopMost = true;
frm2.Show();
}
If you already opened the form elsewhere, then this code will not work as it's a new instance of Form2 and not the one that is opened.
You will have to keep a reference to the form that is opened, and then use Focus or might be better Activate on it.
if the form is opened from within Form1 then:
Add a field for holding current reference of Form2
Save it when showing the form.
Use it when focusing
private Form2 currentForm2;
....
this.currentForm2 = new Form2();
this.currentForm2.Show();
...
...
this.currentForm2.Activate();

Close two form by one click?

I'm working on project with sign in feature
When I run the project there is a form (form1) run the sign in .
after i click on login button build another form (form2) - It's the form of my program .
and made the first form (form1) hide .
The problem is when I press at the X button in form2 it's close but the form1 it's still running .
I tried to close the form1 instead of hide ... but this will close form2 before launching
In form1:
this.Hide();
Form2 x = new Form2();
x.Show();
I think you have your forms around the wrong way.
Form1 sould be your app and shold show Form2 as a dialog when it first loads, then when it closes you can process the result and decide wether to continue or close the application.
Something like:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
Form2 myDialog = new Form2();
if (myDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
{
// failed login
// exit application
}
// all good, continue
}
}
You could subscribe to the child forms FormClosed event and use that to call Close on the parent form.
x.FormClosed += new FormClosedEventHandler(x_FormClosed);
void x_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
try this, in the log in button if access is granted
private void logInBtn_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.ShowDialog();
this.Hide();
}
then in form2 if you want to exit
private void exitBtn_Click(object sender, EventArgs e)
{
Application.Exit();
}
hope this helps.
You go to your form2 then in the event of the form look for FormClosed.
Put this code in your eventhandler:
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
FormClosed is the event whenever the user closes the form. So when you close the form put a code that will exit your application that is -applicationn.exit();-
Hope this will work.

Opening a new form, closing the old one C#

I'm kinda new to C# and I'm doing self study by trying to make a program with a variety of functions to teach myself how to work with C#. I usually look at the internet if I don't know something but this has been driving me crazy.
I remember in the very beginning i started this that I wanted to open a form and close the old one, but when i closed the new form, the old form would reappear again, and other weird varieties of this issue. this.Hide() didn't seem to do anything either.
Currently for opening a new form I'm using this code, but it feels like there should be something with 1 line of code for something as simple as opening a form...
My question is if there is.
private void OpenMainForm()
{
MainForm frm2 = new MainForm();
frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
frm2.Show();
// Since this.Hide() for some reason doesn't work, i'll have to do this crap
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
If you want to hide your main window when you're in the secondary one, you should use the ShowDialog() method. With that, you won't even need the form_closed event.
Your code should look like:
private void OpenMainForm()
{
MainForm frm2 = new MainForm();
this.Hide(); //Hide the main form before showing the secondary
frm2.ShowDialog(); //Show secondary form, code execution stop until frm2 is closed
this.Show(); //When frm2 is closed, continue with the code (show main form)
}
You can also use this code:
public static void ThreadProc()
{
Form2 f;
Application.Run(new Form2());
}
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}
This works perfectly for me
Form2 frm = new Form2();
frm.Show();
frm.Activate();
this.Hide();
but if you want to close the whole application from Form2...you have to add Application.Exit(); in FormClosing event of Form2
You can hide old form as below.
private void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Hide();
}

How to open a new form from another form

I have form which is opened using ShowDialog Method. In this form i have a Button called More.
If we click on More it should open another form and it should close the current form.
on More Button's Click event Handler i have written the following code
MoreActions objUI = new MoreActions ();
objUI.ShowDialog();
this.Close();
But what is happening is, it's not closing the first form. So, i modified this code to
MoreActions objUI = new MoreActions ();
objUI.Show();
this.Close();
Here, The second form is getting displayed and within seconds both the forms getting closed.
Can anybody please help me to fix issue. What i need to do is, If we click on More Button, it should open another form and close the first form.
Any kind of help will be really helpful to me.
In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:
// MainForm
private ChildForm childForm;
private MoreForm moreForm;
ButtonThatOpenTheFirstChildForm_Click()
{
childForm = CreateTheChildForm();
childForm.MoreClick += More_Click;
childForm.Show();
}
More_Click()
{
childForm.Close();
moreForm = new MoreForm();
moreForm.Show();
}
You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.
If I got you right, are you trying like this?
into this?
in your Form1, add this event in your button:
// button event in your Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog(); // Shows Form2
}
then, in your Form2 add also this event in your button:
// button event in your Form2
private void button1_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3(); // Instantiate a Form3 object.
f3.Show(); // Show Form3 and
this.Close(); // closes the Form2 instance.
}
ok so I used this:
public partial class Form1 : Form
{
private void Button_Click(object sender, EventArgs e)
{
Form2 myForm = new Form2();
this.Hide();
myForm.ShowDialog();
this.Close();
}
}
This seems to be working fine but the first form is just hidden and it can still generate events. the "this.Close()" is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with
this.Show();
Best of luck!
I would use a value that gets set when more button get pushed closed the first dialog and then have the original form test the value and then display the the there dialog.
For the Ex
Create three windows froms
Form1 Form2 Form3
Add One button to Form1
Add Two buttons to form2
Form 1 Code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool DrawText = false;
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
if (f2.ShowMoreActions)
{
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
Form2 code
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public bool ShowMoreActions = false;
private void button1_Click(object sender, EventArgs e)
{
ShowMoreActions = true;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
Leave form3 as is
Try this..
//button1 will be clicked to open a new form
private void button1_Click(object sender, EventArgs e)
{
this.Visible = false; // this = is the current form
SignUp s = new SignUp(); //SignUp is the name of my other form
s.Visible = true;
}
private void Button1_Click(object sender, EventArgs e)
{
NewForm newForm = new NewForm(); //Create the New Form Object
this.Hide(); //Hide the Old Form
newForm.ShowDialog(); //Show the New Form
this.Close(); //Close the Old Form
}
you may consider this example
//Form1 Window
//EventHandler
Form1 frm2 = new Form1();
{
frm2.Show(this); //this will show Form2
frm1.Hide(); //this Form will hide
}
For example, you have a Button named as Button1. First click on it it will open the EventHandler of that Button2 to call another Form you should write the following code to your Button.
your name example=form2.
form2 obj=new form2();
obj.show();
To close form1, write the following code:
form1.visible=false;
or
form1.Hide();
You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.
It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.
You need to control the opening of sub forms from a main form.
In my case I'm opening a Login window first before I launch my form1. I control everything from Program.cs. Set up a validation flag in Program.cs. Open Login window from Program.cs. Control then goes to login window. Then if the validation is good, set the validation flag to true from the login window. Now you can safely close the login window. Control returns to Program.cs. If the validation flag is true, open form1. If the validation flag is false, your application will close.
In Program.cs:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
//Validation flag
public static bool ValidLogin = false;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
if (ValidLogin)
{
Application.Run(new Form1());
}
}
}
In Login.cs:
private void btnOK_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "x" && txtPassword.Text == "x")
{
Program.ValidLogin = true;
this.Close();
}
else
{
MessageBox.Show("Username or Password are incorrect.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
Use this.Hide() instead of this.Close()
Do this to Program.cs
using System;
namespace ProjectName
{
public class Program
{
[STAThread]
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetDefaultCompatibleTextRendering(false);
new Form1().Show();
Application.Run();
}
}
}

Categories

Resources