Menu ---
  • Home
  • Tutorials
  • Useful codes
  • Nuget Packages
    • Extension Methods
    • Filter Descriptor for Kendo UI
  • Downloads
    • Active Directory Managing Utility DLL
    • SQL connection methods DLL
  • Contact

C# tutorials and useful codes.

Simple login form with remember me and logout function

Tags c#, login, logoff, remember me, while, while loop, winform1704 Views

In the past few weeks I was asked to create a simple login form by several developers. In this short useful code you’ll see a login form with logoff and remember me function on the main form. Some of the properties was modified in code and not in design mode, so you’ll see how the form got its final design.

The remember me function will use a simple INI file to store and read userdata.

After creating a new Windows Form project in your Visual Studio (let’s call the project LoginFormSample), let’s create this simple class that will check/read/write our INI file:

internal class IniFile
{
    public readonly string Path;
    private readonly string _exe = Assembly.GetExecutingAssembly().GetName().Name;

    [DllImport("kernel32")]
    static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

    [DllImport("kernel32")]
    static extern int GetPrivateProfileString(string section, string key, string Default, StringBuilder retVal, int size, string filePath);

    public IniFile(string iniPath = null)
    {
        Path = new FileInfo(iniPath ?? _exe + ".ini").FullName;
    }

    public string Read(string key, string section = null)
    {
        var retVal = new StringBuilder(255);
        GetPrivateProfileString(section ?? _exe, key, "", retVal, 255, Path);
        return retVal.ToString();
    }

    public void Write(string key, string value, string section = null)
    {
        WritePrivateProfileString(section ?? _exe, key, value, Path);
    }

    public void DeleteKey(string key, string section = null)
    {
        Write(key, null, section ?? _exe);
    }

    public void DeleteSection(string section = null)
    {
        Write(null, null, section ?? _exe);
    }

    public bool KeyExists(string key, string section = null)
    {
        return Read(key, section).Length > 0;
    }
}

With this class we can manage easily our key-value paired INI file. We will have 2 keys in this file: username and password. The values are those values that you enter in your login form WITHOUT any encryption!

The logic of ‘Did I close or logout the application‘ is in the Program.cs file with a simple while loop. Also in this Program.cs file we initialize our INI file: if it doesn’t exist, we create it.

using System;
using System.IO;
using System.Windows.Forms;

namespace LoginFormSample
{
    static class Program
    {
        internal static bool Logoff = true;//because of the first run
        internal static readonly string IniFilePath = Path.GetFullPath(Environment.CurrentDirectory);
        internal static readonly IniFile IniFile = new IniFile(Path.Combine(IniFilePath, "Settings.ini"));

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (!File.Exists(IniFile.Path))
            {
                File.Create(IniFile.Path);
            }

            while (Logoff)
            {
                Logoff = false;
                Application.Run(new Form1());
            }
        }
    }
}

As you can see the default Form1 will be our login form and we should add a new form that will be our main form. Let’s add this new form to our project: frmMain

Now the solution directory should look something like this:

Let’s jump over to our main form. For this logout function we only need a LOGOUT button with its click event subscription (either you double click on the button in design mode or write the subscription code in form constructor). Also I like to set the main form starting position to CenterParent, so it will be opened right at the place of the login form.

namespace LoginFormSample
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();

            StartPosition = FormStartPosition.CenterParent;
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            Program.Logoff = true;
            Close();
        }
    }
}

Now what we are expecting from our login form?

  • hide the typed in password with some special character (like *)
  • the remember me option should work like this:
    • if we place a tick, save the credentials in the INI file and next time when we want to login, fill the textboxes with these information
    • if we remove the tick, clear all the stored credentials from the INI file
  • check if username and password fields are not empty when trying to login
  • possibility to close the application without signing in

I created a form like this in Visual Studio:

…but I modified some of the properties in code, so when running the application, you may see this form:

These small modifications are made in the form constructor:

public Form1()
{
    InitializeComponent();

    //Font = new Font("Microsoft Sans Serif", 10); //modified in design mode, so all the components' size will be automatically modified
    //Size = new Size(400, 300); //modified in design mode
    StartPosition = FormStartPosition.CenterScreen;
    FormBorderStyle = FormBorderStyle.None;
    MaximizeBox = false;
    MinimizeBox = false;

    txbPassword.PasswordChar = '*';

    txbUsername.Select();

    RememberMeRead();
}

The RememberMeRead() function will try to read the INI file and fill the textboxes:

private void RememberMeRead()
{
    if (Program.IniFile.KeyExists("username") && !string.IsNullOrEmpty(Program.IniFile.Read("username")))
    {
        txbUsername.Text = Program.IniFile.Read("username");
        txbPassword.Text = Program.IniFile.Read("password");
        chkRemember.Checked = true;
        btnLogin.Select();
    }
}

If we simple click the EXIT button, we close our form and it will exit the application:

private void btnExit_Click(object sender, EventArgs e)
{
    Close();
}

The login click event will call the RememberMeWrite() function and opens a new instance of the main form while hiding itself (the login form -> this). To be sure you free up the memory after closing a form, always try to use the using keyword when instantiating a new form. When we close our main form, the main thread will jump back here at the end of the using part and closes itself and give the control back to the Main method of the Program.cs class

private void btnLogin_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txbUsername.Text.Trim()) && !string.IsNullOrEmpty(txbPassword.Text.Trim()))
    {
        RememberMeWrite();

        using (frmMain mainForm = new frmMain())
        {
            Hide();
            mainForm.ShowDialog();
        }

        Close();
    }
    else
    {
        MessageBox.Show(@"Missing username and/or password!");
    }
}

When creating a some login and/or registration form, please always use Trim() method of string.

The RememberMeWrite() method:

private void RememberMeWrite()
{
    if (chkRemember.Checked)
    {
        Program.IniFile.Write("username", txbUsername.Text.Trim());
        Program.IniFile.Write("password", txbPassword.Text.Trim());
    }
    else
    {
        Program.IniFile.Write("username", "");
        Program.IniFile.Write("password", "");
    }
}

Let’s see the logout and remember me logic:

  • user starts the program, the Logoff vairable is true, so we step into the while loop
  • we immediately set this variable to false and open the Form1 form (login form)
  • we try to read the credentials from the INI file in this form constructor. If credentials are exist, we fill the 2 textboxes, automatically check the remember me checkbox (we suppose user still wants to store the credentials) and focus on the Login button
  • when pressing the Login button and all the textboxes have values, we write these data into the INI file if the remember me checkbox is checked. If this checkbox is not checked, we clear all the credentials in the INI file
  • we open the main form and hide the login form. Because we only hide it, it still exists in background and ‘eats’ memory.
  • we use ShowDialog, that means this login_Click event will continue only if we close the main form (either with close or logout button, it doesn’t matter)
  • when the main form is closed, we close this login form too and give the control back to the while loop in Program.cs
  • if we pressed the logout button in main form, this ‘while’ loop will start over, otherwise the program exits

The working code can be downloaded here (Visual Studio 2017 and .NET framework 4.7.2):

LoginFormSample.zip (550 downloads)

Post Navigation

Previous Post:

How to create (encode) and decode QR code?

JSON tutorial result in Notepad++
Next Post:

How to serialize and deserialize JSON?

Related Posts:

XML – SQL – custom object

Invoice printing from WinForm application

Creating splash screen for WinForm application

Site Sidebar

Recent Posts

  • How to show enum description in ComboBox?
  • How to serialize and deserialize JSON?
  • Simple login form with remember me and logout function
  • How to create (encode) and decode QR code?
  • How to use generic repository pattern?

Categories

  • ASP.NET
  • C#
  • Entity Framework
  • MVC
  • SQL
  • Tutorials
  • Useful codes

My personal website

Software Development

Site Footer

You can find me on social networks:

Tags

anonymous method asp.net bind binding blackjack bootstrap business logic layer c# cmtrace connectionstring context css csv dal data access layer datatable decoding delegate encoding entity framework enum event excel exception game html ip address listbox log4net mvc n-tier notepad++ remember me repository pattern secure sql sqlconnection subscribe textbox try catch ui unit of work user interface web winform
Created by Attila Török - https://www.crushsoft.eu

Sliding Sidebar

About Me

About Me

In the past years I worked on almost every part of information technology: planning, implementing, managing server infrastructures, supporting desktops for hundreds of end users, planning wired and wireless networks in home offices and large companies, designing and building web sites using CMS mostly, developing softwares to windows based computers, to android equipments and web applications and services, creating video footages and photo shooting.

Tags

anonymous method asp.net bind binding blackjack bootstrap business logic layer c# cmtrace connectionstring context css csv dal data access layer datatable decoding delegate encoding entity framework enum event excel exception game html ip address listbox log4net mvc n-tier notepad++ remember me repository pattern secure sql sqlconnection subscribe textbox try catch ui unit of work user interface web winform