Windows Form Desktop application Log out - c#

On start of my Application Login Form comes up I have simply stored username and password and compared for validating user, if user is valid than MDIparent Form gets opened, Now I want to create logout for this Application. How I can do this?
When I searched I Found That I can do this on FormClosing Event or FormClosed Event but what code should be written in that and for which form, only Dispose(); is enough or something more?
What if I want Login Form to get displayed back?
Showing MDI Form after Successful Login Like this
private void login_Click(object sender, EventArgs e)
{
//if password true then send true
bool value = namePasswordEntry(getHashedUserName, txtUserName.Text, getHashedPassword, txtPassword.Text);
if (value ==true)
{
MessageBox.Show("Thank you for activation!");
this.Hide();
Form2 pfrm = new Form2(txtUserName.Text);
pfrm.ShowDialog();
}
else
{
MessageBox.Show("Invalid LoginName or Password..");
}
}

Try the following codes in the form closing event
Application.Exit(); - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
System.Environment.Exit(1); - Terminates this process and gives the underlying operating system the specified exit code.
Application.Restart() - Shuts down the application and starts a new instance immediately.
Source : http://msdn.microsoft.com/

You Should try this on cancel button or your form closing event........................... Application.Exit();

if (value ==true)
{
MessageBox.Show("Thank you for activation!");
this.Hide();
Form2 pfrm = new Form2(txtUserName.Text);
pfrm.ShowDialog();
pfrom.Dispose(); //because user has logged out so the data must be flushed, by "Disposing" it will not be in the RAM anymore, so your hanging problem will be solved
this.Show(); //just add this line here
}
To Logout using Link Label you just need to raise the click event of it. Write this code in the Form2 constructor:
linkLabel1.Click += linkLabel1_Click;
and then create a method:
void linkLabel1_Click(object sender, EventArgs e)
{
this.Close();
}

If anyone still needs this solution:
private void logoutButton_Click(object sender, EventArgs e)
{
this.close();
}

Related

Receiving password input using DialogShow() not working

I am writing a WinForm application in C#. There is a Form A that opens Form C on Button click. Now, I want to add a password input screen Form B before opening Form C. Only if the password entered is correct will Form C open, and otherwise, show an error message. Form B just has a TextBox control and a Verify Button control.
/*Form A*/
FormB fb;
private void BtnClick(object sender, EventArgs e) {
DialogResult result;
//fb can open once at a time
if(fb == null){
fb = new FormB();
fb.FormClosed += new FormClosedEventHandler(FormB_FormClosed);
//This seems to be not working
result = fb.ShowDialog();
}
else //FormB already open. Do nothing
return;
//Only if password entered is correct, proceed
if(result == DialogResult.Yes){ //result == cancel
//Code to open Form C //Program never reaches here
}
}
//Upon closing FormB, reset it to null
private void FormB_FormClosed(object sender, FormClosedEventArgs e){
if(fb != null)
fb = null;
}
/* Form B */
private const string password = "xxxyyyzzz";
private void BtnPW_Click(object sender, EventArgs e){
bool result = Verify();
if(result){
BtnPW.DialogResult = DialogResult.Yes;
}
else{
MessageBox.Show("Error: Incorrect password");
BtnPW.DialogResult = DialogResult.No;
}
this.Close(); //Added
}
private bool Verify(){
if(TxtBox.Text == password)
return true;
else
return false;
}
Can someone tell me what is wrong with this code? It never reaches the second if statement in Form A.
Edit: Even if I enter the correct password and hit the button on Form B, result in Form A gets "DialogResult.Cancel`.
If you call the Form.Close method, then the DialogResult property of that form is set to DialogResult.Cancel even if you have set it to something else. To HIDE a form opened modally you just need to set the form's DialogResult property to anything but DialogResult.None.
Said that your code seems to be not the one usually used to handle a modal dialog.
ShowDialog is blocking your code, you don't exit from this call until the called form is closed or hidden, so you don't need to keep a global variable of FormB around and handle the FormClosed event handler of FormB in FormA.
private void BtnClick(object sender, EventArgs e)
{
using(FormB fb = new FormB())
{
// Here the code returns only when the fb instance is hidden
result = fb.ShowDialog();
if(result == DialogResult.Yes)
{
//open Form C
}
}
}
Now you should remove the call to Form.Close in the FormB code and set directly the DialogResult property of the FormB, do not try to change at this point the DialogResult property of the buttons, this will not work and you need a second click to hide the form, instead set directly the form's DialogResult property.
private const string password = "xxxyyyzzz";
private void BtnPW_Click(object sender, EventArgs e)
{
if(Verify())
this.DialogResult = DialogResult.Yes;
else
{
MessageBox.Show("Error: Incorrect password");
this.DialogResult = DialogResult.No;
}
}
In this way the form is hidden (not closed) and your code exits from the ShowDialog call in the FormA. Inside the using block you can still use the FormB instance to read its properties and take the appropriate paths. When your code exits from the using block the fb instance will be automatically closed and disposed out of existence.

WPF close all window from the main window

I have login window. From this login window, i am intializing the main window.
Once login successfully happened, i close the login window.
Now i am having two other windows, which i am calling from Main Window.
Once i close the main Window, I am able to close the other two windows as well as Main Window.
But program still runs in memory. I have to close it manually from the Visual Studio.
How should i close the Program all instances fully??
This is the Main window Close Event code.
private void usimClose(object sender, EventArgs e)
{
newScreen2.Close();
newScreen3.Close();
this.Close();
}
This is my Login Window Code. Once the user click on the submit button.
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
if (txtUserName.Text.Length == 0)
{
errormessage.Text = "Please Enter UserName";
txtUserName.Focus();
}
else
{
LoginStatus _status = _Login.LoginUsimgClient(txtUserName.Text, txtPassword.Password.ToString());
if (_status.BoolLoginstatus)
{
mainWindow.RunApplication();
string struserName = _status.StringUserFirstName;
mainWindow.userName.Text = "Welcome " + struserName;
mainWindow.Show();
this.Close();
}
else
{
errormessage.Text = _status.StringErrorDescription;
txtUserName.Text = String.Empty;
txtPassword.Password = String.Empty;
}
}
}
Try Application.Current.Shutdown();
From MSDN
Calling Shutdown explicitly causes an application to shut down,
regardless of the ShutdownMode setting. However, if ShutdownMode is
set to OnExplicitShutdown, you must call Shutdown to shut down an
application.
Important note
When Shutdown is called, the application will shut down irrespective
of whether the Closing event of any open windows is canceled.
This method can be called only from the thread that created the
Application object.
You can close all windows using this
App.Current.Shutdown();
or
you can manually close it
Window parentwin = Window.GetWindow();
parentwin.Close();
If you starting point is your MainWindow, then just start there.
Firstly, host the LoginForm in your MainWindow, and show it using ShowDialog() to force the user to interact with the LoginForm. Return the result of a successful/unsuccessful interaction to the MainForm.
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
var form = new LoginForm();
var result = form.ShowDialog();
if (result ?? false)
{
// Carry on opening up other windows
}
else
{
// Show some kind of error message to the user and shut down
}
}
Otherwise, technically your LoginForm is hosting your MainForm which is, frankly, odd.
Have a look at my answer here: How to close wpf window from another project
An Application.Current.Shutdown() will stop the application in a very abrupt way.
It is better to gracefully keep track of the windows and close them.

Invoke event handler on a different form after closing the active form

I have a C# application in which I need specific or a function to execute on a form after closing the active form.
The form in which I need the code to excute becomes the active form after the previous active form is closed. So in a nutshell after closing this form the form in which I need the event handler or function to run will then become the active form. Is there a way that this is possible?
I have tried the Form_Enter event handler on the form that becomes active after the other form is closed, but that did not work.
I believe you can achieve what you are trying to do more simply. The code you use to show Form2 from Form1 (Main), you can add your code there like so:
Class Form1 {
private void button_click(object sender, EventArgs e) {
Form2 newForm = Form2();
newForm.ShowDialog(); // To prevent the main form carry on
// Your code needed to be excuted
}
}
In the form closing event set the DialogResult as follows:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Yes;
}
When you open the form look for the response as follows:
if (Form1.ShowDialog() == DialogResult.Yes)
{
////do stuff.
}
I hope this helps.

How can I fire an event so my other form reacts to it?

I have this form called MainForm.cs. When I click Enter The Progam button I display another form using the .ShowDialog() method.
In this new form called LoginBox.cs, I check if the entered credentials are valid and if they are I want my MainForm.cs to react with either a positive responde (the actual software form opens) or negative response a MessageBox alerting him of the failure.
It's a very simple use case, but I don't know how to solve this correctly and efficiently. Thank you.
private void button1_Click(object sender, EventArgs e)
{
LoginBox login = new LoginBox();
login.ShowDialog();
}
//And in the LoginBox.cs file:
private void button1_Click(object sender, EventArgs e)
{
if ((txtUser.Text == "admin") && (txtPassword.Text == "123"))
{
}
}
If you open the form with ShowDialog it returns a DialogResult which you can check in your main form.
LoginBox login = new LoginBox();
DialogResult dialogResult = login.ShowDialog();
if (dialogResult == DialogResult.OK)
{
// etc...
}
You can set the value of DialogResult in your LoginBox form:
DialogResult = DialogResult.OK;
Others have mentioned using DialogResult, which can work--but might be abused a bit in this use-case. Its intended purpose is to let the parent form know what the user did on a child form--did they click OK or Cancel? Did they click Retry or Abort? It's not intuitive that it should be used for authentication purposes.
So--what's better? Probably a combination...
Your LoginBox class is a Dialog, so returning a DialogResult should be expected--but should also only be used to indicate what the user did on the Form, not the outcome of the authentication.
I would suggest looking into the usage of some other dialogs, such as OpenFileDialog. It returns a DialogResult to specify whether to go ahead with the file opening, but it doesn't actually open the file until being explicitly told to do so. This means the consuming code has to both check the result and instruct the dialog to perform it's function, so it's not perfectly simple--but it's fairly conventional.
Here's an example of how I would suggest you use LoginBox:
private void button1_Click(object sender, EventArgs e)
{
LoginBox login = new LoginBox();
if (login.ShowDialog() == DialogResult.OK) // Let the user input their credentials and click OK or Cancel
{
if (!login.ValidateCredentials) // Perform the authentication with the collected credentials
{
MessageBox.Show("The specified Credentials were invalid!");
}
}
}
Add an Event to the LoginBox. Then have the MainForm handle that event. In the event handler proceed with the additional logic that you want to perform.

ObjectDisposedException when Multiple Forms Are Open

My C# Winform application encounters the situation where it cannot access a disposed object. The disposed object is a form (frmQuiz) that is opened from a button on the login form.
The Situation:
My application typically has two or three forms open at the same time. The Program.cs file runs form frmLoginBackground, which is just a semi-transparent background that covers the computer screen. The load event for this form opens the second form, frmLogin, which includes a button that opens frmQuiz, which is a simple form with a few math questions on it.
The code in frmLogin that opens frmQuiz looks like this:
private void btnTakeQuizNow_Click(object sender, EventArgs e)
{
frmQuiz quiz = new frmQuiz();
quiz.TakeQuizNow("take_quiz_now", Convert.ToInt32(comboQuizMeNow.SelectedValue)); //Pass the form a quiz id number.
quiz.Show();
}
When frmQuiz opens both it and frmLogin are open and accessible.
The frmLogin also contains a password control that opens the administration form by first opening frmSplash, which is a "Please Wait..." splash form based on a timer. The timer Tick event launches frmAdmin, which is the administration form. The code in frmLogin looks like this:
private void btnPasswordSubmit_Click(object sender, EventArgs e)
{
//Password verification code snipped.
frmSplash objSplash = new frmSplash();
objSplash.Show();
//this.Hide();
this.Close();
}
And the code in frmSplash looks like this:
private void timer1_Tick(object sender, EventArgs e)
{
frmAdmin objfrmAdmin = new frmAdmin ();
objfrmAdmin.Show();
this.Close();
}
When frmAdmin opens then frmLogin is no longer accessible; however, frmAdmin contains a 'Return to Login Screen' button with code like this:
private void btnReturnToLogin_Click(object sender, EventArgs e)
{
exitWarnings("return_to_login");
}
private void exitWarnings(string action)
{
//Warning message code snipped.
if (action == "return_to_login")
{
frmLogin objLogin = new frmLogin();
objLogin.Show();
}
}
The frmLoginBackground remains open until the application exits.
The Problem:
Everything works fine when frmLogin first opens and the button is clicked to open frmQuiz. The quiz form opens a runs fine. However, after logging into the administration form (which closes or hides the login form) and then clicking the 'Return to Login Screen' link, then, after frmLogin reappears, the object disposed exception occurs when clicking the button to open frmQuiz. Visual Studio highlights in yellow the "quiz.Show();" line of code. The exception occurs regardless of weather I use "this.Close();" or "this.Hide();" in the btnPasswordSubmit_Click event.
Can anyone suggest a solution that allows me to open frmQuiz after returning to frmLogin from frmAdmin.
Cheers, Frederick
Since you create a new instance for quizz just before the quizz.Show() it cannot be quizz itself that throws the exception.
Take a good look at the constructor and FormCreate event of frmQuiz. It looks like that is where the dead horse is being kicked.

Categories