.NET Forum / Languages / C# / March 2008
Ending a program while in Form_Load
|
|
Thread rating:  |
Dom - 25 Mar 2008 22:09 GMT How do I end a program while in Form_Load? I tried both this.Close(), and Application.Exit(), but neither will just end the program there and then. Instead, both allow Form_Load to continue.
Peter Duniho - 25 Mar 2008 22:27 GMT > How do I end a program while in Form_Load? I tried both this.Close(), > and Application.Exit(), but neither will just end the program there > and then. Instead, both allow Form_Load to continue. Well, I suppose you could just throw an exception, or just put a "return" statement after your call to Application.Exit(). That would prevent the rest of your Load event handler from executing.
The Application.Exit() method isn't like the old CRT "exit()" function. It doesn't terminate the process. It just signals to the application message pumps to stop and closes all the windows.
I'm not aware of a .NET equivalent to "exit()", though of course an unhandled exception can terminate the application, albeit messily. You should avoid implementing code that just terminates the process. It's extremely unlikely that there's a good reason for wanting to do this, and you're better off exiting your application cleanly.
Pete
Jon Skeet [C# MVP] - 25 Mar 2008 22:59 GMT > > How do I end a program while in Form_Load? I tried both this.Close(), > > and Application.Exit(), but neither will just end the program there [quoted text clipped - 13 lines] > extremely unlikely that there's a good reason for wanting to do this, and > you're better off exiting your application cleanly. Environment.Exit() is *reasonably* close to exit() I believe.
 Signature Jon Skeet - <skeet@pobox.com> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet World class .NET training in the UK: http://iterativetraining.co.uk
Peter Duniho - 25 Mar 2008 23:11 GMT >> I'm not aware of a .NET equivalent to "exit()" [...] > > Environment.Exit() is *reasonably* close to exit() I believe. Perhaps. The docs are extremely vague on exactly how it operates, but yes...it appears reasonably close to exit().
Still, I wouldn't recommend it as a correct way of exiting a .NET Forms application. :)
Pete
Willy Denoyette [MVP] - 26 Mar 2008 00:01 GMT >>> I'm not aware of a .NET equivalent to "exit()" [...] >> [quoted text clipped - 5 lines] > Still, I wouldn't recommend it as a correct way of exiting a .NET Forms > application. :) Why not? Environment.Exit performs an "orderly shutdown" of the managed execution environment, before an orderly shutdown of the unmanaged environment is initiated.
Willy.
Peter Duniho - 26 Mar 2008 00:29 GMT >> Still, I wouldn't recommend it as a correct way of exiting a .NET Forms >> application. :) [quoted text clipped - 3 lines] > environment, before an orderly shutdown of the unmanaged environment is > initiated. As far as I understand it, there's "orderly" and then there's _orderly_.
I take as granted that Environment.Exit() isn't going to leave managed stuff hanging, but it doesn't know anything about the logic or data of the application itself. I wouldn't use exit() as a normal strategy for exiting an unmanaged Windows application, and I wouldn't use Environment.Exit() as a normal strategy for exiting a managed Windows application.
Pete
Willy Denoyette [MVP] - 26 Mar 2008 01:19 GMT >>> Still, I wouldn't recommend it as a correct way of exiting a .NET Forms >>> application. :) [quoted text clipped - 14 lines] > > Pete Oh, but I'm not promoting this as a "normal strategy" to end an application, and IMO this is not what the OP is after, why would he otherwise need to end an application while handling a form_load event?.
Anyway, with Environment.Exit, there is always a possibility to perform some "application state clean-up" by registering an AppDomain.ProcessExit event handler, this is a reasonable strategy to apply when you have to deal with situations where you want to terminate a process who's (damaged) state requires it to terminate as soon as possible . This handler will be called as a last chance to run some managed code (time constrained to a max. of 3 seconds per AppDomain), before the managed environments starts it's orderly shutdown activity, which consists in starting the GC and the finalizer thread and give him a reasonable chance to run the reachable and unreachable Finalizers. So, IMO you have a fair chance to clean-up after you, if you care.
Note that calling exit() now ((since msvcrt v 7.1 (net 1.1) ),redirects the call into Environment.Exit whenever called from a process that runs managed code, this is done to make it possible to start an "orderly shutdown" from a unmanaged code.
Willy.
Peter Duniho - 26 Mar 2008 01:40 GMT >>>> Still, I wouldn't recommend it as a correct way of exiting a .NET >>>> Forms application. :) [quoted text clipped - 8 lines] > application, and IMO this is not what the OP is after, why would he > otherwise need to end an application while handling a form_load event?. You're assuming he does. All we know is that he _believes_ he does.
That said, I'm happy to amend my original statement so that rather than saying "a .NET Forms application" instead it says "the vast majority of .NET Forms applications". If the OP has some unusual need in which he cannot afford to simply return from the Load event handler after calling Application.Exit(), then yes...Environment.Exit() may well solve this problem.
Pete
Dom - 26 Mar 2008 16:12 GMT Let me give the full picture, in case there is a better way to handle everything.
In a dataentry program, the Form_Load event fires up a modal dialogue box, in which the user can enter his/her name and password, and choose which part of the project to work on. It makes sure that the user does not choose a part that someone else is currently working on. On THIS form, the user can back out (in case the available parts of the project are not to his level of expertise) by clicking on cancel.
Of course, after Cancel is clicked on, the program goes back to the initial Form_Load, and I want to just end it there.
Dom
On Mar 25, 8:40 pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com> wrote:
> On Tue, 25 Mar 2008 17:19:02 -0700, Willy Denoyette [MVP] > [quoted text clipped - 22 lines] > > Pete Ignacio Machin ( .NET/ C# MVP ) - 26 Mar 2008 16:20 GMT > Let me give the full picture, in case there is a better way to handle > everything. [quoted text clipped - 42 lines] > > - Show quoted text - Hi,
I think that calling Close() if the result of the dialog is not correct will do the trick. Also Application.Exit should do it, when the app goes to process the next messages it will see it and will terminate the app.
Also take a look in the archives for something ilke "password dialog" or password form
Peter Duniho - 26 Mar 2008 18:27 GMT > Let me give the full picture, in case there is a better way to handle > everything. [quoted text clipped - 8 lines] > Of course, after Cancel is clicked on, the program goes back to the > initial Form_Load, and I want to just end it there. Thanks for the elaboration.
Personally, I would attempt to prevent the main form from ever being created until you know for sure you want to display it. I would do this by something along these lines:
In your main form .cs file:
class MainForm : Form { public MainForm() { InitializeComponent(); }
static public MainForm Prompt() { using (PromptForm prompt = new PromptForm()) { if (prompt.ShowDialog() == DialogResult.OK) { return new MainForm(); } }
return null; } }
In the Program.cs file:
static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
MainForm main = MainForm.Prompt();
if (main != null) { Application.Run(main); } } }
Hope that helps.
Pete
Dom - 26 Mar 2008 18:39 GMT On Mar 26, 1:27 pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com> wrote:
> > Let me give the full picture, in case there is a better way to handle > > everything. [quoted text clipped - 63 lines] > > Pete Interesting. I never thought of that. I'll have to give it a try.
Dom
Ignacio Machin ( .NET/ C# MVP ) - 26 Mar 2008 22:17 GMT On Mar 26, 1:27 pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com> wrote:
> > Let me give the full picture, in case there is a better way to handle > > everything. [quoted text clipped - 14 lines] > created until you know for sure you want to display it. I would do this > by something along these lines: I agree with you. But maybe his main form is just a splash form, if so it would make sense to display it
Peter Duniho - 26 Mar 2008 23:41 GMT > I agree with you. But maybe his main form is just a splash form, if so > it would make sense to display it I'm not sure what you mean. The OP has made it very clear that he wants to optionally continue with the program based on the user's response to a _dialog_. I don't think there's any "maybe" about this hypothetical splash form of which you speak.
On the other hand, if one is talking more generally about how to display a splash form, sure...that's possible and wouldn't involve any conditional stuff based on the display of that form. But I'm not sure how that'd be relevant in this thread.
Pete
Dom - 27 Mar 2008 16:41 GMT On Mar 26, 6:41 pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com> wrote:
> On Wed, 26 Mar 2008 14:17:57 -0700, Ignacio Machin ( .NET/ C# MVP ) > [quoted text clipped - 13 lines] > > Pete Pete got it right. I don't want the main form shown at all if the user cancels from the dialog that comes before it. The dialog gives the user the options that are available at the moment, none of which may be appropriate.
Pete's solution worked fine for me.
Dom
RobinS - 27 Mar 2008 16:45 GMT >> Let me give the full picture, in case there is a better way to handle >> everything. [quoted text clipped - 14 lines] >created until you know for sure you want to display it. I would do this >by something along these lines: What would be wrong with doing this? I need to display a login form and do authentication, and if the user doesn't authenticate, or he hits Cancel, I need to shut down the app. The main form uses information that is not available until the user authenticates.
In the Program.cs file:
static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
bool showMain = false; using (PromptForm prompt = new PromptForm()) { if (prompt.ShowDialog() == DialogResult.OK) { showMain = true; } }
if (showMain) { Application.Run(main); } } }
RobinS.
Peter Duniho - 27 Mar 2008 17:00 GMT > What would be wrong with doing this? I need to display a login form and > do authentication, and if the user doesn't authenticate, or he hits > Cancel, I need to shut down the app. The main form uses information that > is not available until the user authenticates. I'm not sure I understand the question. The code you posted is practically the same as what I posted, except that
-- you put the prompt into the Main() method instead of in the form class -- you used a boolean instead of a reference to the form instance -- it doesn't compile
Assuming you fix the last difference, I don't find the other two differences to be material differences. You can do it either way and it's fine.
One potential advantage to putting the prompt in the form class is that if it's setting up information that the form class will need to instantiate itself, all of that code can reside inside the form class where all the related stuff stays together.
But obviously you could just make that data available in the Program class instead. And if all that's really going on is that the data is collected directly from the prompt dialog and passed to the main form constructor, then whether that happens in the Main() method or a static method in the form class makes practically no difference.
Though, I'd say in that case it may make more sense to instantiate the main form inside the "if" statement checking the result of the prompt dialog, so that you can just get the data straight from the prompt dialog rather than storing it in local variables and using it later (i.e. replace the boolean variable with a simple reference to the form, initialized to null and left that way if the dialog is canceled or the form otherwise can't be instantiated).
But really, that's a long-winded way of saying: you can do it either way, and there's no fundamental difference between the alternatives. They are all basically the same thing, with very minor differences in the implementation details.
Pete
RobinS - 27 Mar 2008 17:54 GMT >> What would be wrong with doing this? I need to display a login form and >> do authentication, and if the user doesn't authenticate, or he hits [quoted text clipped - 38 lines] > > Pete Thanks. I wasn't sure if there was some "rule" about opening forms in program.cs or not. I used to be a VB programmer and as you've pointed out, switching to C# isn't just about the syntax.
The reason I used a local variable and checked it before doing Application.Run was so I could dispose of the dialog box before continuing on my merry way. Although you're right, I could have instantiated the main form, then checked it for null.
Thanks again. RobinS.
Dom - 28 Mar 2008 14:44 GMT > >> What would be wrong with doing this? I need to display a login form and > >> do authentication, and if the user doesn't authenticate, or he hits [quoted text clipped - 52 lines] > > - Show quoted text - You know what I just thought of? In Program.cs, I did this (of course, it is much like what Pete and Robin did):
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
bool Cancel = false; frmMain.frmMain_Init(ref Cancel); if (!Cancel) { Application.Run(new frmMain()); } }
This puts it in the right place (the Main Form), and it brings back that nice Form_Init event that VB had but had to be gotten rid of in C#. I'm a little surprised this doesn't come up as automatic code in the IDE.
Jon Skeet [C# MVP] - 25 Mar 2008 22:31 GMT > How do I end a program while in Form_Load? I tried both this.Close(), > and Application.Exit(), but neither will just end the program there > and then. Instead, both allow Form_Load to continue. Can you call Application.Exit and then return? Making Form_Load finish is as simple as returning from it.
 Signature Jon Skeet - <skeet@pobox.com> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet World class .NET training in the UK: http://iterativetraining.co.uk
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|