winform auto close if main form is closed - c#

I have two .net 2 winforms, each has its own project. project 1 is main form and project 2 is a child form. and now I would like to know how to make the child form close it self if main form is no longer active.
killing child form on exit doesnt work, because main form can be killed by task manager.

you need to handle the OnClosing event of main form where you can close any child forms.You need to have a member variable of a child form in main.

If I understand correctly, what you call a 'child form' is actually another WinForms app running in a separate process?
In addition, I take it (from your "because main form can be killed by task manager" comment) that you want the exiting behaviour to be resilient to cases when the main-app is forcefully killed.
One way would be to get the 'child app' to listen to the Process.Exited event of the 'main app', and exit if it fires.
I imagine it would look something like:
public Form1()
{
InitializeComponent();
// You need to figure out how best to do this part.
// Also, what to do if the main-app isn't already running.
var mainAppProcess = Process.GetProcessesByName("MainApp").First();
mainAppProcess.EnableRaisingEvents = true;
// Close the form when the other process exits.
mainAppProcess.Exited +=
delegate { BeginInvoke(new Action(Close)); };
}

Related

Exit whole app c# with close button [duplicate]

I have a published application in C#. Whenever I close the main form by clicking on the red exit button, the form closes but not the whole application. I found this out when I tried shutting down the computer and was subsequently bombarded by lots of child windows with MessageBox alerts I added.
I tried Application.Exit but it still calls all the child windows and alerts. I don't know how to use Environment.Exit and which integer to put into it either.
Also, whenever my forms call the FormClosed or FormClosing event, I close the application with a this.Hide() function; does that affect how my application is behaving?
From MSDN:
Application.Exit
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.
Environment.Exit
Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.
This article, Application.Exit vs. Environment.Exit, points towards a good tip:
You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
if (System.Windows.Forms.Application.MessageLoop)
{
// WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Console app
System.Environment.Exit(1);
}
Reference: Why would Application.Exit fail to work?
I know this is not the problem you had, however another reason this could happen is you have a non background thread open in your application.
using System;
using System.Threading;
using System.Windows.Forms;
namespace Sandbox_Form
{
static class Program
{
private static Thread thread;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
thread = new Thread(BusyWorkThread);
thread.IsBackground = false;
thread.Start();
Application.Run(new Form());
}
public static void BusyWorkThread()
{
while (true)
{
Thread.Sleep(1000);
}
}
}
}
When IsBackground is false it will keep your program open till the thread completes, if you set IsBackground to true the thread will not keep the program open. Things like BackgroundWoker, ThreadPool, and Task all internally use a thread with IsBackground set to true.
By the way. whenever my forms call the formclosed or form closing event I close the applciation with a this.Hide() function. Does that affect how my application is behaving now?
In short, yes. The entire application will end when the main form (the form started via Application.Run in the Main method) is closed (not hidden).
If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don't intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.
If you want to be able to have the user click the "x" for your main form, but have another form stay open and, in effect, become the "new" main form, then it's a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you'll need to add in some sort of mechanism that will actually close the main form when you really do want your app to end. If this is the situation that you're in then you'll need to add more details to your question describing what types of applications should and should not actually end the program.
In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:
protected override void OnExit(ExitEventArgs e) {
base.OnExit(e);
}

Form Navigation in Win CE 5 Application

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();

How do I properly exit a C# application?

I have a published application in C#. Whenever I close the main form by clicking on the red exit button, the form closes but not the whole application. I found this out when I tried shutting down the computer and was subsequently bombarded by lots of child windows with MessageBox alerts I added.
I tried Application.Exit but it still calls all the child windows and alerts. I don't know how to use Environment.Exit and which integer to put into it either.
Also, whenever my forms call the FormClosed or FormClosing event, I close the application with a this.Hide() function; does that affect how my application is behaving?
From MSDN:
Application.Exit
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.
Environment.Exit
Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.
This article, Application.Exit vs. Environment.Exit, points towards a good tip:
You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
if (System.Windows.Forms.Application.MessageLoop)
{
// WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Console app
System.Environment.Exit(1);
}
Reference: Why would Application.Exit fail to work?
I know this is not the problem you had, however another reason this could happen is you have a non background thread open in your application.
using System;
using System.Threading;
using System.Windows.Forms;
namespace Sandbox_Form
{
static class Program
{
private static Thread thread;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
thread = new Thread(BusyWorkThread);
thread.IsBackground = false;
thread.Start();
Application.Run(new Form());
}
public static void BusyWorkThread()
{
while (true)
{
Thread.Sleep(1000);
}
}
}
}
When IsBackground is false it will keep your program open till the thread completes, if you set IsBackground to true the thread will not keep the program open. Things like BackgroundWoker, ThreadPool, and Task all internally use a thread with IsBackground set to true.
By the way. whenever my forms call the formclosed or form closing event I close the applciation with a this.Hide() function. Does that affect how my application is behaving now?
In short, yes. The entire application will end when the main form (the form started via Application.Run in the Main method) is closed (not hidden).
If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don't intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.
If you want to be able to have the user click the "x" for your main form, but have another form stay open and, in effect, become the "new" main form, then it's a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you'll need to add in some sort of mechanism that will actually close the main form when you really do want your app to end. If this is the situation that you're in then you'll need to add more details to your question describing what types of applications should and should not actually end the program.
In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:
protected override void OnExit(ExitEventArgs e) {
base.OnExit(e);
}

Handle an event in a child form while the parent form is running

Suppose that I have Form1 as a parent from in a MDI Windows forms application.
It has a btnStart button, which simply does a lot of calculation, let say:
double i;
while(blnContinue)
{
i=(i+1)%100000;
}
Form2 is a child with btnStop button, which simply assign blnContinue = false; so that the while loop breaks;
But the point is that, the Form2 cannot raise the event when the btnStop is pressed.
In this case, it's straightforward to make the function containing the while loop in a separate thread and create the btnStop in the parent form.
But I must do the "infinite" while loop in the main thread, so I it's not allowed to
make it as a thread and start/stop it.
Anyone knows how to process the event of the Form2?
Thanks in advance!
You will need to call Application.DoEvents inside the loop, say every 100ms. I don't think there is any other option. Without that your entire app will appear locked and no events will fire anywhere so no chance to do anything. Is there something stopping you using another thread?

Form Closing on X C#

After an immense amount of reasearch I am still no closer to a solution.
I have a simple app, 2 forms .NETv3.5 C#.
The application loads the first form, i press 'X' on the windows bar.
The application hides the form and continues to run without exiting the application even though the only form loaded is closed.
The main form Closing method does not get called when the X is pressed because the form is hidden when the x is pressed. Form.Deactivated is called but not Form.Closing.
How can i catch the the even when the X is pressed ? (Then I can implement Application.Exit())
Check if you have timer or thread that is running. If so stop those.
I guess in Program.cs, you call Application.Run passing the main form as parameter. If so, the app won't exit until the main form closes.
To catch the event when X button is pressed, add event handler to secondary form's Closed event, not the main form's. In that event, call main form's Close method (or Application.Exit).

Categories