最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

winforms - Windows Forms C# : problem with registration system, forms, I don't know how to close the form, switching to

programmeradmin3浏览0评论

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();
            }
        }
    }
}

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();
            }
        }
    }
}
Share Improve this question edited Feb 15 at 6:02 marc_s 755k184 gold badges1.4k silver badges1.5k bronze badges asked Feb 15 at 4:59 DanyDany 51 bronze badge 4
  • I fot to clarify, when I exit the form, I log in and pass for some reason – Dany Commented Feb 15 at 5:50
  • 1 Note that you can edit the question to add new information. – Klaus Gütter Commented Feb 15 at 7:08
  • Application.Exit() followed by Application.Run() is not good. Instead, move this code into your Main() method, before the Application.Run() call there. Example – Hans Passant Commented Feb 15 at 13:12
  • This answer offers some insights on managing the window handles so that things don't hang: stackoverflow/a/78160557/5438626 – IV. Commented Feb 16 at 11:19
Add a comment  | 

2 Answers 2

Reset to default 0

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:

  • When it closes, it will have a dialog result.
  • "When they click on the exit button" the value (by default) will be 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;
}

Application.Exit and Run should not be used when showing forms.

In an attempt to provide a clear answer, I'll use your code and rewrite it in a way that will work better.

A quick, easy way to accomplish this, would be to load your Main Form first in your Program.cs, and then call your Login form, via ShowDialog. This will create a modal window, and you can have the user enter their login.

Inside your TV Form add this:

using System;
using System.Windows.Forms;

namespace TVCourseWork
{
    public partial class TV : Form
    {
        // ... previously defined variables 
        bool isAuthenticated = false; // Lets store the state of the users login via a bool
        public TV() // Lets call the Login form after we initialize the Form.
        {
            InitializeComponent();
            PromptLogin(); // <-- new method
        }
        
        private void PromptLogin()
        {
            using (Login loginForm = new Login()) // Using the Login class, lets create a loginForm object to use to open the Form
            {
                DialogResult result = loginForm.ShowDialog(); // Show the form as a modal dialog
                if (result == DialogResult.OK)
                {
                    isAuthenticated = loginForm.IsLoggedIn; // Get the boolean result from the form.
                    
                    if(isAuthenticated){
                        AdminPanel adminPanel = new AdminPanel(); // Show the admin form if we authenticated
                        adminPanel.Show();
                    }
                    this.Show(); 
                    // Show the main form afterwards even if we aren't authenticated, for non authenticated users
                    // Reading your original Login class this seems like the intended behavior, if its not, and you don't want
                    // unauthenticated users, you can have the application exit if isAuthenticated returns false.
                }
            }
            
        }

        // rest of your code
        
    }
}

And your Login Form should look like:

using System;
using System.Windows.Forms;

namespace TVCourseWork
{
    public partial class Login : Form
    {
        private bool isClosing = false;
        public static 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 (textBox1.Text == correctUsername && textBox2.Text == correctPassword)
            {
                IsLoggedIn = true;
                MessageBox.Show("Вход выполнен успешно!", "Доступ разрешен", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show("Неверный логин или пароль!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
    }
}

This solution should accomplish what you were looking for. Make sure you update your Program.cs to start the TV form first, instead of your Login Form.

If the goal was to have unauthenticated users shown the MainForm and Administrators the admin panel when logged in, this will work.

I don't think spoon feeding code is a good solution in solving problems, but do try to take a look at the flow of the Main form and how it communicates with the login form to accomplish this.

Also, I'm assuming this is temporary, but you really need to link a backend to this project, and not store usernames and passwords in the source code as predefined variables for obvious security concerns.

All in all, good luck with your project and I hope this solution works for you! If it does, please mark it as correct!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论