c# MDI parent form + login form error
I get this error:
Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.
When trying to exit my app after disposing a login form. To clarify, this is what I'm doing in my form:
public frmMainMDI()
{
Initial开发者_运维问答izeComponent();
frmLogin frmLogin_ = new frmLogin(); //create new login form
frmLogin_.ShowDialog(); //show i
if (frmLogin_.DialogResult == DialogResult.Cancel) //if user pressed cancel
{
frmLogin_.Dispose(); //dispose login form
Application.Exit(); //Exit application. If I used this line, it throws the error stated above in Program.cs
//this.Dispose(); //If I try to use this one instead, it throws an 'already disposed' error
//this.Close(); //same error as .dispose
}
else
{
intCurrentLoggedInStaffID = frmLogin_.intStaffID;
}
}
And this is in my program.cs:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMainMDI()); //this is the line that bugs out
}
I don't quite get it. It almost looks like the app is trying to restart itself when I try to .Exit
it. Am I missing something pretty fundamental here? (I'm guessing the answer is 'yes')
I can't quite explain why you are getting this error, but I can suggest a better way to do it. If I understand your intentions correctly, you want to show a login form before the main MDI window is shown and exit your application, if the user pressed cancel in the login form.
Your program.cs:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LoginForm loginForm = new LoginForm();
if (loginForm.ShowDialog() != DialogResult.Cancel)
{
MainMdiForm mainMdiForm = new MainMdiForm();
mainMdiForm.intCurrentLoggedInStaffID = loginForm.intStaffID;
loginForm.Dispose();
loginForm = null;
Application.Run(mainMdiForm);
}
}
Your constructor in the MainMdiForm should only contain the call to InitializeComponents
.
You're attempting to exit the application (which means shut down the main message loop) in the middle of a constructor (which is bad in general) which is being run in the method which is supposed to be starting up that message loop in the first place. So you have contradictory operations going here.
What I would suggest is that you move your login form/dialog code into your program.cs/Main() function. So something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using(frmLogin frmLogin_ = new frmLogin()) { //create new login form
frmLogin_.ShowDialog(); //show i
if (frmLogin_.DialogResult == DialogResult.Cancel) //if user pressed cancel
{
return; // This exits your application
}
}
Application.Run(new frmMainMDI()); //this is the line that bugs out
}
精彩评论