Click here to Skip to main content
Click here to Skip to main content
Go to top

Windows Forms Login Control using C#

, 1 Apr 2014
Rate this:
Please Sign up or sign in to vote.
This article describes how to program a login control for Windows Forms.
Sample Image - maximum width is 600 pixels

Introduction

In this tip, I programmed a login control for Windows Forms. Unlike some usual controls I've seen, in my code I've used delegates and events. This is useful when using the control in a Windows Forms application to handle authentication and logging in processes. These processes are implemented using events in the control. The authentication process is left to the user and then he notifies the control of whether successful login or not, as we will see later.

Background

A delegate is a function pointer. When you declare a delegate, it behaves exactly like a method. You can combine methods of the delegates' signature and combine them together, allowing more than one method to be called at the same time.
Here is an example delegate:

public delegate int PerformCalculation(int x, int y); 

And here are example methods:

int calculate1(int a, int b)
{
    return a + b;
}

int calculate1(int a, int b)
{
    return a - b;
}

Now, you can combine this delegate with another method of the same signature:

PerformCalculation calc1, calc2, calc3;

calc1 = calculate1;
calc2 = calculate2;
calc3 = calc1 + calc2;

Events are a special type of delegates, they provide a way for a class to notify others that something happened. The class that sends the event is called the publisher and the one that receives the event is called subscriber.

You can subscribe to events the same way as delegates, for example, assume the following function to subscribe to a button click event:

public void buttonClick(object s, EventArgs ea)
{
    System.Console.WriteLine("You clicked a button!");
}

// Here is how you add this method
button1.Click += new EventHandler(buttonClick); 

Or you can do it simply like this:

button1.Click += delegate(object s, EventArgs ea)
        {
            System.Console.WriteLine("You clicked a button!");
        }

Events and delegates are one of the most powerful features in .NET. For now, I only gave a light briefing on them, I highly suggest that you go to C# Programming Guide and check some code on how to declare and publish events, it's a great source to learn from.

Login Control Design

The UI of the control contains two textboxes for submitting the username and the password, and a button for starting the authentication process. There are two read-only properties for retrieving the username and password texts:

public string Username 
{
    get { return UserName.Text; }
}
public string Passwordtext
{
    get { return Password.Text; }
}

and three events that the code logic depends on:

public event AuthenticationEventHandler Authenticate;
public event EventHandler LoggedIn;
public event EventHandler LoggedError;

The Authenticate event indicates that process of authenticating the user is started. The LoggedIn event indicates that the user is successfully authenticated and is logged in. The LoggedError event indicates that some error happened during authenticating the user like username is incorrect, for example.

In all the events, I didn't need a custom EventArgs class. For the Authenticate event, I needed a delegate as follows:

public delegate bool AuthenticationEventHandler(object sender, EventArgs e);

The bool returned value indicates whether the user is authenticated or not, based on the user's implementation of the Authenticate event.

The Authenticate Event and the Asynchronous Event Trigger

Let's say you have multiple authentication methods in your program. In order to execute all the subscribing delegates, I had to use an asynchronous method to raise the event to all the subscribers. Logically, this case should be considered only in the Authenticate event as follows using the Delegate.BeginInvoke method: [Source]

protected void OnAuthenticate(EventArgs e)
{
    AuthenticationEventHandler authHandler = Authenticate;
    if (authHandler != null)
    {
        foreach (AuthenticationEventHandler handler in authHandler.GetInvocationList())
        {
            handler.BeginInvoke(this, e, new AsyncCallback(Callback), handler);
        }
    }
}

and the Callback method:

void Callback(IAsyncResult ar)
{
    AuthenticationEventHandler d = (AuthenticationEventHandler)ar.AsyncState;
    if (d.EndInvoke(ar))
    {
        OnLoggedIn(new EventArgs());
    }
    else
    {
        OnLoggedError(new EventArgs());
    }
}

That's why the AuthenticationEventHandler delegate is declared as a bool return type.

Add the Control to your Project to be Dragged into the Form

After successfully building the project, getting the DLL file and adding a reference to it in your project, in your Visual Studio, go to Tools > Options:

In the Options window, from the left pane, go to Windows Forms Designer > General.

And check that the variable "Automatically Populate Toolbox" is set to True. After that, go to Tools > Choose Toolbox Items:

In the .NET Framework Components tab, check if your DLL is in the list, if not click browse, locate it and select it, your control should appear in the toolbox under "General" tab ready to be dragged into the form:

Points of Interest

For each textbox, there is the keydown event implemented, just if you are used to pressing the Enter key:

void UserName_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        OnAuthenticate(new EventArgs());
    }
}

And there is a tiny error handling mechanism for which if the text boxes are empty:

private void UserName_TextChanged(object sender, EventArgs e)
{
    if (UserName.Text.Trim().Length == 0)
    {
        label3.Text = "*";
    }
    else
    {
        label3.Text = "";
    }
}

private void Password_TextChanged(object sender, EventArgs e)
{
    if (Password.Text.Trim().Length == 0)
    {
        label4.Text = "*";
    }
    else
    {
        label4.Text = "";
    }
}

And one last note is in your application form load event, after you insert your control, you must subscribe to the control's events.
For example, like this:

private void Form1_Load(object sender, EventArgs e)
{
    this.loginControl1.Authenticate += loginControl1_Authenticate;
    this.loginControl1.LoggedIn += loginControl1_LoggedIn;
    this.loginControl1.LoggedError += loginControl1_LoggedError;
}

Any Future Updates?

Right now, I'm planning for a feature on how to provide a data source of both the username and the password and the control internally authenticates and verifies the user. Your comments are welcome on this feature. Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Abdallah Al-Dalleh
Engineer
Jordan Jordan
I'm a computer engineer, interested in hardware, software and security.
 
Always trying to learn new topics, to seek a decent computer engineering career!

Comments and Discussions

 
QuestionNice work PinmemberEmejulu JVT10-Apr-14 0:45 
AnswerRe: Nice work PinmemberAbdallah Al-Dalleh10-Apr-14 1:55 
GeneralMy vote of 2 Pinmemberleiyangge1-Apr-14 15:10 
GeneralRe: My vote of 2 PinmemberAbdallah Al-Dalleh1-Apr-14 19:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 1 Apr 2014
Article Copyright 2014 by Abdallah Al-Dalleh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid