C# Threading process - c#

Program.cs
using (Login login = new Login())
{
login.ShowDialog(); //Close this form after login is correct in login form button_click
}
if (isValiduser == true) //Static variable created in application to check user
{
Application.Run(new MainInterface());
}
Login form click event
private void btnLogin_Click(object sender, EventArgs e)
{
if(isValiduser == true)
{
this.Close();
}
else
{
//else part code
}
}
According to this code when we Click on Login event in Login form and isValiduser return true then Program.cs will run MainInterface form. but actually, this code is not run Application.Run(new MainInterface());
So, could anyone tell me what's wrong with this code?

Your code in Program.CS should be
using (Login login = new Login())
{
login.ShowDialog(); //Close this form after login is correct in login form button_click
if (isValiduser == true) //Static variable created in application to check user
{
Application.Run(new MainInterface());
}
}
And your login click event should be like that
private void btnLogin_Click(object sender, EventArgs e)
{
if(isValiduser == true)
{
//this.Close();
this.DialogResult = DialogResult.OK;
}
else
{
//else part code
}
}

problem is you are not set isValiduser as true in your code. so it will newer run MainInterface form.
Assume you have defined static variable called isValiduser in your Program.cs file as
static class Program
{
public static bool isValiduser = false;
[STAThread]
static void Main()
{
// rest of your code
And then when you click login button you need to set this variable based on login status.
you may need to have separate method for this.
private void btnLogin_Click(object sender, EventArgs e)
{
// call validate user method and set value to `isValiduser`
Program.isValiduser= IsValidUser("username", "password"); // here for testing i'm set it as true
if(Program.isValiduser== true)
{
this.Close();
}
else
{
//else part code
}
}
you can have method to validate users
private bool IsValidUser(string name, string pw)
{
return true; // impliment this method
}

What I suspect is happening is that when you get to the this.Close() the control goes back to the main thread and the application ends (if there is no further code after it). i.e Your program starts from the first line of the main and ends at the last. So if you open your login form first then you need to open the MainInterface form before closing the login form.

Related

How can I debug an issue with a wrapper class causing this.Close() to hang upon form loading?

I'm writing an application that has a login form show prior to launching the main application. If the form is not allowed to load (the form checks for existing credentials and validates them, if successful the form is closed in the form_load event) then the application continues along swimmingly. However, if those credentials don't exist or are not correct then the form finishes loading and presents itself as a login form for the user.
When the user enters their information they then click a submit button which triggers a round of validation identical to above and then closes.
The login form does close (visibly) but never returns a result to the main program.
Main:
DialogResult result;
using (LoginForm lf = new LoginForm())
result = lf.ShowDialog();
if (result == DialogResult.OK)
{
Application.Run(new LibraryForm());
}
else
{
Application.Exit();
}
From the login form:
private void loginMaterialButton_Click(object sender, EventArgs e)
{
if (usernameTextBox.Text == "")
{
MessageBox.Show("You must enter a valid sharepoint user email for authentification!");
}
else if (passwordTextBox.Text == "")
{
MessageBox.Show("You must enter a valid sharepoint password for authentification!");
}
else
{
if (UpdateCredentials())
{
try
{
CloseOut();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void LoginForm_Load(object sender, EventArgs e)
{
if (CheckExistingCredentials())
{
CloseOut();
}
}
private void CloseOut()
{
this.DialogResult = DialogResult.OK;
this.Close();
}
I made a second barebones LoginForm with only standard winform components and it worked as expected, however I'm not sure what the best course of action is to determine what exactly is causing the login form to not return on close?
Here is the github link for the package I'm using to wrap the winform:
https://github.com/leocb/MaterialSkin
Mystery solved:
https://github.com/leocb/MaterialSkin/issues/67
The issue is within this library, apparently something holds up the return of DialogResult when using the password characters in a ShowDialog form.

Windows Forms Application - Closing login form exits application [duplicate]

I have two forms in my project (Login and Main).
What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.
I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
var main = new Main();
main.Show();
this.Close();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?
What should be the right approach for this?
Thanks...
The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.
The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:
static void Main()
{
LoginForm fLogin = new LoginForm();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
else
{
Application.Exit();
}
}
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
private void MainForm_Load(object sender, EventArgs e)
{
this.Hide();
LogonForm logon = new LogonForm();
if (logon.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
this.Show();
}
}
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm logon = new LogonForm();
Application.Run(logon);
if (logon.LogonSuccessful)
{
Application.Run(new MainForm());
}
}
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials
This is my solution. Create ApplicationContext to set mainform of application and change mainform when you want to open new form and close current form.
Program.cs
static class Program
{
static ApplicationContext MainContext = new ApplicationContext();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainContext.MainForm = new Authenticate();
Application.Run(MainContext);
}
public static void SetMainForm(Form MainForm)
{
MainContext.MainForm = MainForm;
}
public static void ShowMainForm()
{
MainContext.MainForm.Show();
}
}
When login process is complete.
private void BtLogin_Click(object sender, EventArgs e)
{
//Login Process Here.
Program.SetMainForm(new Portal());
Program.ShowMainForm();
this.Close();
}
I hope this will help you.
It's simple.
Here is the code.
private void button1_Click(object sender, EventArgs e)
{
//creating instance of main form
MainForm mainForm = new MainForm();
// creating event handler to catch the main form closed event
// this will fire when mainForm closed
mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
//showing the main form
mainForm.Show();
//hiding the current form
this.Hide();
}
// this is the method block executes when main form is closed
void mainForm_FormClosed(object sender, FormClosedEventArgs e)
{
// here you can do anything
// we will close the application
Application.Exit();
}
This is the most elegant solution.
private void buttonLogin_Click(object sender, EventArgs e)
{
MainForm mainForm = new MainForm();
this.Hide();
mainForm.ShowDialog();
this.Close();
}
;-)
Here's a simple solution, your problem is that your whole application closes when your login form closes right? If so, then go to your projects properties and on the Application Tab change the shutdown mode to "When last form closes" that way you can use Me.close without closing the whole program
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login();
}
private static bool logOut;
private static void Login()
{
LoginForm login = new LoginForm();
MainForm main = new MainForm();
main.FormClosed += new FormClosedEventHandler(main_FormClosed);
if (login.ShowDialog(main) == DialogResult.OK)
{
Application.Run(main);
if (logOut)
Login();
}
else
Application.Exit();
}
static void main_FormClosed(object sender, FormClosedEventArgs e)
{
logOut= (sender as MainForm).logOut;
}
}
public partial class MainForm : Form
{
private void btnLogout_ItemClick(object sender, ItemClickEventArgs e)
{
//timer1.Stop();
this.logOut= true;
this.Close();
}
}
I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.
Try this:
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
t.Start();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
[STAThread]
public void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.
One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.
Hope this helps.
you should do it the other way round:
Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform
EDIT:
As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.
best way for show login for and close login form before login successfully put login form in FrmMain after InitializeComponent.
public FrmMain()
{
FrmSplash FrmSplash = new FrmSplash();
FrmSplash.ShowDialog();
InitializeComponent();
//Login Section
{
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Hide();
var main = new Main();
main.Show();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
try this
private void cmdLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "admin" || txtPassword.Text == "1")
{
FrmMDI mdi = new FrmMDI();
mdi.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect Credentials", "Library Management System", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
and when you exit the Application you can use
Application.Exit();
Evan the post is too old i like to give you a trick to do this if you wants to show splash/login screen and when the progress bar of splash screen get certain value/or successful login happen and closed the splash/login then re show the main form, frm-main will be the startup form not frm-spalash
in frm-main
public partial class frmMain : Form
{
public frmMain()
{
frmSplash frm = new frmSplash();
frm.Show(); // new splash screen will shows
this.Opacity=0; // will hide your main form
InitializeComponent();
}
}
in the frm-Splash
private void timer1_Tick(object sender, EventArgs e)
{
int cnt = progressBar1.Value;
switch (cnt)
{
case 0:
//Do sum stuff
break;
case 100:
this.Close(); //close the frm-splash
frmMain.ActiveForm.Opacity = 100; // show the frm-main
break;
}
progressBar1.Value = progressBar1.Value+1;
}
if you use it for login form
private void btlogin_Click(object sender, EventArgs e)
{
bool login = false;
//try your login here
//connect your database or whatever
//and then when it success update login variable as true
if(login == true){
this.Close(); //close the frm-login
frmMain.ActiveForm.Opacity = 100; // show the frm-main
}else{
//inform user about failed login
}
}
note that i use a timer and a progress bar to manipulate the actions you don't need those two it just for sake of complete answer only, hope this helps
1.Go to MainMenu Design properties> Go to my events
2.Click MainMenu event Shown and show LoginForm
3.Leave MainMenu as the First run in Program.cs

How to use a method from the Startup form to enable its controls when called through a child form?

I am trying to enable admin privileges on my startup form. For this I've created an admin toolstrip login which would cause a password form to launch. I am however unable to update the startup form through the password form. I've seen a similar article over here [Why the controls not update, when call method from other form but this hasn't helped me solve my problem. My code is as below and what I have achieved so far is as below:
// Code for startup form...
public partial class StartupForm : Form {
private void adminToolStripMenuItem_Click(object sender, EventArgs e) {
FrmAdminPassword frmAdminPassword = new FrmAdminPassword();
frmAdminPassword.Show();
//this.Close();
//AdminLogin();
}
public void AdminLogin() {
loginToolStripMenuItem.Enabled = false;
logoutToolStripMenuItem.Enabled = true;
cmb1.Enabled = true;
btn1.Enabled = true;
tab1.Enabled = true;
tab2.Enabled = true;
tabControl1.TabPages.Add(tabAdminTasks);
MessageBox.Show("Admin Logged In");
}
}
// Code for password form
public partial class FrmAdminPassword : Form {
private void btnLoginAdmin_Click(object sender, EventArgs e) {
if (mskAdminPassword.Text == "password") {
StartupForm frm = new StartupForm();
frm.Show();
frm.AdminLogin();
this.Close();
}
else {
MessageBox.Show("Not a valid password");
this.Close();
}
}
}
If I implement it this way, what happens is that the original instance of the startup form is still present as a duplicate instance with all tabs and controls disabled and a new form is launched with all controls enabled.
What I actually want to achieve is:
Click on the adminToolStripMenuItem.
Launch the FrmAdminPassword.
Enter the password and hit Login on FrmAdminPassword.
After hitting Login, close the FrmAdminPassword and enable the controls on StartupForm.
Could someone please help on this? Thanks.
Use ShowDialog() to show your login form. This will stop the execution of code in the startup form until the login form closes
private void adminToolStripMenuItem_Click(object sender, EventArgs e)
{
// Putting the creation of the form inside a using block allows
// the automatic closing and disposing of the form when the code
// reaches the closing brace of the using block.
using(FrmAdminPassword frmAdminPassword = new FrmAdminPassword())
{
// This opens the frmAdminPassword form in modal mode, no
// code is executed after the call until you close the
// form with DialogResult.OK, DialogResult.Cancel or whatever
if(DialogResult.OK == frmAdminPassword.ShowDialog())
{
MessageBox.Show("Login executed with success!");
}
else
{
// Mo password given or form cancelled
// put here the logic to exit or disable things
}
}
}
Now in the Login form OK button click you could execute your logic to validate the password and to allow the closing of the form if the password match
public partial class FrmAdminPassword : Form
{
private void btnLoginAdmin_Click(object sender, EventArgs e)
{
if (mskAdminPassword.Text == "password")
this.DialogResult = DialogResult.OK;
else
{
MessageBox.Show("Not a valid password");
this.DialogResult = DialogResult.None;
}
}
}
To make this work you need to set the DialogResult property of the Login Form to something different from DialogResult.None. This Will force the Login form to automatically hide (not close) so you can read the DialogResult property on the initial instance of the startup form and decide what to do next. You should also provide some method to exit from the login form with DialogResult.Cancel and stop further processing because the user decided to not give a password.
Try this...
FrmAdminPassword
private void btnLoginAdmin_Click(object sender, EventArgs e)
{
if (mskAdminPassword.Text == "password")
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
else
{
MessageBox.Show("Not a valid password");
this.Close();
}
}
StartupForm
private void adminToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmAdminPassword frmAdminPassword = new FrmAdminPassword();
using(frmAdminPassword)
{
if(frmAdminPassword.Show() == System.Windows.Forms.DialogResult.OK)
{
AdminLogin();
}
}
}
What is happening is that you have two separate copies of the form instantiated. At launch, the startup form is instantiated. During login, you are instantiating a totally new copy. Your login needs to reference the existing startup form.

public bool var not updating its value

I've created a public bool LogedIn; in my login.cs:
if(login successful condition)
LogedIn = true;
else
LogedIn = false
But when I access this var from another form with Login Log = new Login();
by using if(Log.LogedIn) the LogedIn variable is always false, even after successful login by the user.
Why this is not working/updating its value outside its parent form?
Updating the code:
Login.cs
public bool isLogedIn;
private void button1_Click(object sender, EventArgs e)
{
if (i>-1 && (textBox2.Text == DS.Tables[0].Rows[--i][0].ToString()))
{
this.DialogResult = DialogResult.OK;
isLogedIn = true;
}
else
{
MessageBox.Show("Invalid password supplied for username \"" + comboBox1.Text + "\"", "Login Error.....", MessageBoxButtons.OK);
isLogedIn = false;
return;
}
}
Checking for the updated value in Home.cs
private void Home_Load(object sender, EventArgs e)
{
if (Log.isLogedIn) // Always False at this position.
{
label18.ForeColor = System.Drawing.Color.Green;
submitButton.Enabled = true;
}
else
{
label18.ForeColor = System.Drawing.Color.Red;
submitButton.Enabled = false;
}
}
I've checked again... I'm not having double instance of this variable in Login.cs form.
Here's how I'm calling Login.cs form via Home.cs (main form). Hope this helps...
private void loginToolStripMenuItem_Click(object sender, EventArgs e)
{
Log.FormClosed += new FormClosedEventHandler(Log_FormClosed);
Log.ShowDialog(this);
Log.BringToFront();
}
void Log_FormClosed(object sender, FormClosedEventArgs e)
{
if (Log.isLogedIn)
{
// Something here
}
else
{
// Something here
if (Log.DialogResult == DialogResult.Cancel)
Log.Hide();
}
}
I assume you have a form called Login in your application. Ignore the rest if assumption is wrong.
You are not referring to the correct instance of the Login form. In windows application, there is a collection called Application.OpenForms. This contains all the open form instances in your application. To access the correct Login form, try this:
Application.OpenForms.OfType<Form>().Where(x => x is Login).FirstOrDefault()
Make sure you have Login form always open to perform this task. You can make use of Hide instead of Close or CloseDialog for the Login form.
If you are closing the Login form, you can create static class which is accessible from each of the forms keep the properties there.
It seems that you have more than one instance of the Login class, each one with its isLogedIn var.
It is not clear where you are instantiating Login with your Login Log = new Login(); line. Have you tried to put a breakpoint there and see how many times it gets hit?
Another thing you could do is put a breakpoint on the line where isLogedIn is set, and another one where you read it. When the setting breakpoint is hit add a watch to the instance of Login (in this case add a watch to this) and choose Make Object ID from the right click menu. Your instance will be marjked by a "#1" Then do the same for the variable Log when the reading breakpoint is hit. If the mark is different (i.e. "#2") you can be sure that you are reading something different from the variable you set before.

How can I close a login form and show the main form without my application closing?

I have two forms in my project (Login and Main).
What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.
I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
var main = new Main();
main.Show();
this.Close();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?
What should be the right approach for this?
Thanks...
The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.
The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:
static void Main()
{
LoginForm fLogin = new LoginForm();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
else
{
Application.Exit();
}
}
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
private void MainForm_Load(object sender, EventArgs e)
{
this.Hide();
LogonForm logon = new LogonForm();
if (logon.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
this.Show();
}
}
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm logon = new LogonForm();
Application.Run(logon);
if (logon.LogonSuccessful)
{
Application.Run(new MainForm());
}
}
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials
This is my solution. Create ApplicationContext to set mainform of application and change mainform when you want to open new form and close current form.
Program.cs
static class Program
{
static ApplicationContext MainContext = new ApplicationContext();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainContext.MainForm = new Authenticate();
Application.Run(MainContext);
}
public static void SetMainForm(Form MainForm)
{
MainContext.MainForm = MainForm;
}
public static void ShowMainForm()
{
MainContext.MainForm.Show();
}
}
When login process is complete.
private void BtLogin_Click(object sender, EventArgs e)
{
//Login Process Here.
Program.SetMainForm(new Portal());
Program.ShowMainForm();
this.Close();
}
I hope this will help you.
It's simple.
Here is the code.
private void button1_Click(object sender, EventArgs e)
{
//creating instance of main form
MainForm mainForm = new MainForm();
// creating event handler to catch the main form closed event
// this will fire when mainForm closed
mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
//showing the main form
mainForm.Show();
//hiding the current form
this.Hide();
}
// this is the method block executes when main form is closed
void mainForm_FormClosed(object sender, FormClosedEventArgs e)
{
// here you can do anything
// we will close the application
Application.Exit();
}
This is the most elegant solution.
private void buttonLogin_Click(object sender, EventArgs e)
{
MainForm mainForm = new MainForm();
this.Hide();
mainForm.ShowDialog();
this.Close();
}
;-)
Here's a simple solution, your problem is that your whole application closes when your login form closes right? If so, then go to your projects properties and on the Application Tab change the shutdown mode to "When last form closes" that way you can use Me.close without closing the whole program
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login();
}
private static bool logOut;
private static void Login()
{
LoginForm login = new LoginForm();
MainForm main = new MainForm();
main.FormClosed += new FormClosedEventHandler(main_FormClosed);
if (login.ShowDialog(main) == DialogResult.OK)
{
Application.Run(main);
if (logOut)
Login();
}
else
Application.Exit();
}
static void main_FormClosed(object sender, FormClosedEventArgs e)
{
logOut= (sender as MainForm).logOut;
}
}
public partial class MainForm : Form
{
private void btnLogout_ItemClick(object sender, ItemClickEventArgs e)
{
//timer1.Stop();
this.logOut= true;
this.Close();
}
}
I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.
Try this:
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
t.Start();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
[STAThread]
public void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.
One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.
Hope this helps.
you should do it the other way round:
Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform
EDIT:
As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.
best way for show login for and close login form before login successfully put login form in FrmMain after InitializeComponent.
public FrmMain()
{
FrmSplash FrmSplash = new FrmSplash();
FrmSplash.ShowDialog();
InitializeComponent();
//Login Section
{
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Hide();
var main = new Main();
main.Show();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
try this
private void cmdLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "admin" || txtPassword.Text == "1")
{
FrmMDI mdi = new FrmMDI();
mdi.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect Credentials", "Library Management System", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
and when you exit the Application you can use
Application.Exit();
Evan the post is too old i like to give you a trick to do this if you wants to show splash/login screen and when the progress bar of splash screen get certain value/or successful login happen and closed the splash/login then re show the main form, frm-main will be the startup form not frm-spalash
in frm-main
public partial class frmMain : Form
{
public frmMain()
{
frmSplash frm = new frmSplash();
frm.Show(); // new splash screen will shows
this.Opacity=0; // will hide your main form
InitializeComponent();
}
}
in the frm-Splash
private void timer1_Tick(object sender, EventArgs e)
{
int cnt = progressBar1.Value;
switch (cnt)
{
case 0:
//Do sum stuff
break;
case 100:
this.Close(); //close the frm-splash
frmMain.ActiveForm.Opacity = 100; // show the frm-main
break;
}
progressBar1.Value = progressBar1.Value+1;
}
if you use it for login form
private void btlogin_Click(object sender, EventArgs e)
{
bool login = false;
//try your login here
//connect your database or whatever
//and then when it success update login variable as true
if(login == true){
this.Close(); //close the frm-login
frmMain.ActiveForm.Opacity = 100; // show the frm-main
}else{
//inform user about failed login
}
}
note that i use a timer and a progress bar to manipulate the actions you don't need those two it just for sake of complete answer only, hope this helps
1.Go to MainMenu Design properties> Go to my events
2.Click MainMenu event Shown and show LoginForm
3.Leave MainMenu as the First run in Program.cs

Categories

Resources