I have an issue regarding the login and password system. I recently started working with C#, and as a student, I need to write a password and login system that allows the user to exit the form when they click on the exit button, even if the fields are empty.
However, when I press the exit button, the
private void button1_Click(object sender, EventArgs e)
event handler is triggered. If I enter the correct or incorrect password, everything works as expected, but as soon as I click the exit button, the password system stops working.
What could be causing this and how can I resolve it? Please help
using System;
using System.Windows.Forms;
namespace TVCourseWork
{
public partial class Login : Form
{
private bool isClosing = false;
private bool IsLoggedIn = false;
private string correctUsername = "admin";
private string correctPassword = "1234";
TV mainForm = new TV();
public Login()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
if (isClosing || IsLoggedIn)
return;
if (textBox1.Text == correctUsername && textBox2.Text == correctPassword)
{
IsLoggedIn = true;
MessageBox.Show("Вход выполнен успешно!", "Доступ разрешен", MessageBoxButtons.OK, MessageBoxIcon.Information);
AdminPanel adminPanel = new AdminPanel();
this.Hide();
adminPanel.ShowDialog();
this.Show();
}
else
{
MessageBox.Show("Неверный логин или пароль!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!isClosing && !IsLoggedIn)
{
var result = MessageBox.Show("Вы уверены, что хотите выйти без входа?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
isClosing = true;
Application.Exit();
Application.Run(mainForm);
}
else
{
e.Cancel = true;
}
}
else if (IsLoggedIn)
{
isClosing = true;
Application.Exit();
Application.Run();
}
}
}
}
My goal in answering this is to hopefully provide some basic concepts to assist you in writing code in your personal style that you can turn in for your assignment.
You're describing a LoginForm
that is being (or should be) shown modally, via a ShowDialog()
command. Here's what's important right now:
DialogResult.Cancel
.So, what you need to make sure of is that this form returns DialogResult.OK
only under very strict conditions. It needs to collect a UID and it needs to get a password and then employ some scheme to validate that user. (This minimal example skips the last step. If you've got a pulse then you're in).
If the login form looks something like this:
...then it must perform those checks and if everything looks good make the [Login] button visible. When this button is clicked it will set the DialogResult
property to DialogResult.OK
and this closes the dialog window.
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
// This is to make sure the placeholder hint is visible
// which it won't be if the control is given focus.
Shown += (sender, e) => ActiveControl = null;
textBoxUid.TextChanged += localUpdateVisibility;
textBoxPswd.TextChanged += localUpdateVisibility;
void localUpdateVisibility(object? sender, EventArgs e)
{
textBoxPswd.Visible = !string.IsNullOrWhiteSpace(textBoxUid.Text);
buttonLogin.Visible = textBoxUid.Visible && !string.IsNullOrWhiteSpace(textBoxPswd.Text);
}
buttonLogin.Click += (sender, e) => DialogResult = DialogResult.OK;
}
}
NOTE: For clarity and brevity, the events in the code above are subscribed using lambda expressions, which are "anonymous" functions that have no identifier. We also employ a local function since it provides a utility that is useful only within this scope.
Main Form
The main form keeps itself hidden intil a valid login takes place.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
_ = Handle;
BeginInvoke(() =>
{
using (var loginForm = new LoginForm())
{
if (DialogResult.OK == loginForm.ShowDialog())
{
isLoggedIn = true;
Show();
}
else
{
MessageBox.Show("Not Authorized");
Close();
}
}
});
}
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(value && isLoggedIn);
}
bool isLoggedIn;
}