C#/.NET: how do I close the application from a parent window? - c#

I have a Windows application that has 2 Forms. From one form I am opening a 2nd form.
When opening the 2nd form I am hiding 1 form and in the second foem I am starting a thread.
Now I want to close the application.
But I was not able to do that.
On my 1st form I have tried:
Form1 frm = new Form1(this, tcpClient);
frm.ShowDialog();
this.Close();
Application.Exit();
But the application is not ending. It still running.
Any idea how to stop that?
EDIT (CODE Included):
On 1st form's button click event:
this.Hide();
Form1 frm = new Form1(this, tcpClient, serverMsg);
frm.Show();
On 1st form's button FormClosed event:
MessageBox.Show("Before");
Application.Exit();
On 2nd form's load event I am calling a method startThread(); on this method
ilThread = new Thread(incomingListener);
ilThread.IsBackground = true;
ilThread.Start();

When you do frm.ShowDialog() you're opening a modal window. The code will stop at that point until you specify a DialogResult on frm. I.e. frm.DialogResult = DialogResult.Ok;.
If you use frm.Show() that might work for you.

Edit- See #GenericTypeTea's answer first. If after doing that you are still having issues see mine:
From what you describe it sounds like you have left the thread running. Have you tried creating the thread as a background thread or making sure you end that thread in a clean way?

You probably didn't set the Thread you started as a background thread. Background threads are stopped automatically when application closes. Foreground threads will keep it alive.
To set thread as background thread use IsBackground property.
See Thread.IsBackground.
Otherwise you should take care yourself of stopping the started thread before exiting the application.

Related

Modeless form doesn't receive the input focus

I have a Windows Form ("form1") which is opened with ShowDialog() in the main thread of application just before Application.Run() is called ( without that form as the argument ). From the main thread another thread ("thread2") is created, which runs in parallel with the main thread. With pressing a button in the "form1", another form ("form2") is created in the "thread2" and shown with Show() method. The problem: the "form2" doesn't get the input focus and doesn't receive keyboard or mouse input.
The form2 is created as follows:
public form2( )
{
InitializeComponent();
this.WindowState = FormWindowState.Normal;
this.TopMost = true;
this.SetStyle( ControlStyles.Selectable, true );
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Bounds = Screen.PrimaryScreen.Bounds;
}
I created a handler on OnFocusLosing event which writes a string to the console, and see that the form2 is losing focus just after creation. Is it the form1, which is opened with ShowDialog() and runs in the main thread grabs the focus back? I tried to minimize the form1 before creating the form2, but it doesn't help.
How one can get a form to receive the input focus?
As far as I know there is only ever a single UI thread in a Windows Forms application, you can't just spawn off threads and expect the user to be able to interact with them.
You could try this if you really need two independent UI threads: https://social.msdn.microsoft.com/Forums/en-US/3f0e7794-8671-47c4-aa9a-3bd1f85c9963/how-to-create-a-winform-app-with-two-ui-threads

MessageBox shown before form closes

Why is the messagebox shown before the form closes?
SomeForm myForm = new SomeForm();
myForm.Show();
MessageBox.Show("Some text");
Do I need to start a new thread, and wait for it to finish? I've never come across this problem before.
You need to use Form.ShowDialog() instead. Form.Show shows a modeless window, whereas Form.ShowDialog shows a modal form, i.e., that the user has to close before continuing.
Your example never actually closes myForm...only shows it. I would expect the code above to show myForm and then immediately show the MessageBox.
If you want myForm to close before showing the MessageBox, you'll need to call myForm.Close() at some point.
The reason for this is that myForm.Show(); starts the opening of a new window, however it is not a blocking call. It's not a dialog, it's a separate window, which runs on it's own.
If you want SomeForm to show as a Dialog (blocking window, waits for close to continue execution), then use ShowDialog. If you want to wait till the window is opened before you show the MessageBox, then add the MessageBox to the OnLoaded on the SomeForm claa.
If it's important that the user not be able to interact with the main form while this other form is being shown then you can use myForm.ShowDialog instead of Show. ShowDialog is a blocking function, so it won't return until the other form is closed. Show, on the other hand, just shows the other form and then immediately returns without waiting for the form to be closed.
If it's intentional that the other form is not being shown modally, and you don't (or can't) make that change, then you can use events to show a message box when the other form is closed.
SomeForm myForm = new SomeForm();
myForm.FormClosed += (form, args) =>
{
MessageBox.Show("Some text");
};
myForm.Show();
This will add an event handler, which fires when the other form is closed, and executes the desired code at the appropriate time.

C# form closing at program end

I have a windows forms question:
Program.cs:
Application.Run(new frmStart());
frmStart: on btnLoad_Click,
frmLoad formLoad = new frmLoad();
formLoad.Show();
this.Hide(); // if I do a this.Close(); after it shuts down and doesn't get to show the form
frmLoad: on btnCancel_Click:
Application.Exit();
// or this.Close();
// or even: base.Close();
The form disappears but the program doesn't end, I still have to press the blue "Stop Debugging" to make it stop.
I have been looking... I know it is possible to make the program really stop, and not just freeze when you close the second form, even if you don't keep the first form on the screen, but can't remember and can't figure out how.
Ack, -1 on Application.ExitThread!
The issue is that you haven't closed the main form. The simplest way is to hook onto the 2nd form's Closed event and have it close the main form. For example the code to open the 2nd form changes to:
var newForm = new frmLoad();
newForm.FormClosed += (closedSender, closedE) => Close();
newForm.Show();
Hide();
This essentially sets up so that when the frmLoad form closes, the main form calls it's Close() method. I used a Lambda expression for the event handler, but you can just as easily create a private method accepting an (object sender, EventArgs e) and point .FormClosed at it.
*Edit: Sorry, missed that you only want to close on certain state. In which case on your frmLoad, create a public property such as:
public bool UserCancelled
{
get;
private set;
}
where the Cancel button sets this to True before closing the form. Your event handler in the main form changes to:
var newForm = new frmLoad();
newForm.FormClosed += (closedSender, closedE) =>
{
if (newForm.UserCancelled)
Close();
};
newForm.Show();
Hide();
In frmStart add:
public static frmStart Current;
Then in the constructor add:
Current = this;
Then in frmLoad: on btnCancel_Click:
frmStart.Current.Close();
You really should call Close() on both. That's the only clean way as otherwise the first form never is told to close down and doesn't clean up.
You may know that it's safe to do this, but someone else working on the code later may add code in the OnClose in the first form that they need called. They will say not nice things about you when they finally figure out why their code is not called.
If you close both, then your app will exit.
Please use the Application.ExitThread() method, the method exits the message loop on the current thread and closes all windows on the thread.
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.exitthread
I vote yuck on all the answers. Override Form Closing in your primary form and close the secondary form first.

How to set a windows form as the main form of the application? C#

I'm using Visual Studio C# and I got stuck in making a new form become the main one. I need the application to be closed when it get closed and I want to close the previous form without closing the application.
Current attempt (won't work):
FormClass newForm = new FormClass();
newForm.Show()
previousForm.Close()
First understand why the Application is exiting. From the documentation of Application.Run(Form):
This method adds an event handler to
the mainForm parameter for the Closed
event. The event handler calls
ExitThread to clean up the
application.
If you can get away with just hiding it rather than closing it
FormClass newForm = new FormClass();
newForm.Show();
previousForm.Hide();
If you need to close it (or would rather)
Alter Program.cs. To prevent the event handler added by Run(Form) from terminating you, use an overload of Run() that doesn't add such a handler:
var form = new Form1();
form.Show();
Application.Run(); // The application will not exit when form is closed
But in this case, you will need to call Application.Exit() yourself when the newForm is closed (or under any other circumstances in which you want to Exit).
If your intent is to use something like a splashscreen, try call the first form on a background thread, them abort the thread after the task if completed. The "first" form will be closed.
Or, just close the "splashscreen form", ending the background thread.
It helps?

C# - window form application - Close the application

I want a help. I have a window form application. Whenever I click on the "close" of the form, the application should itself close.
Can anyone help me.
Regards,
Justin Samuel.
After your explanation:
In Form1, do something like:
Form2 f2 = new Form2();
f2.ShowDialog();
this.Close();
Application.Exit();
This is assuming Form2 can be shown Modal (Dialog), which I think is correct
A Winforms application will exit automatically when the main form is closed. The main form is the form that is instantiated and passed to Application.Run method in the Main method of the application.
If the application process does not exit when this form is closed, something is preventing it from closing, such as a thread (that is not a background thread) that is performing some work.
By your description, it sounds like you may have multiple forms in your application and one form is still running even if its's not visible. In this case, the close button, would close the form, but not exit the application.
You need to add an event handler for the Form_FormClosed event and then call Application.Exit() - Ideally, you could also handle the Form_FormClosing event if you want to give the user a dialog to ask if they really meant to close.
Maybe you are looking for the Application.Exit() method.

Categories

Resources