Click here to Skip to main content
15,884,975 members
Articles / Programming Languages / C#

Windows Forms Login Control using C#

Rate me:
Please Sign up or sign in to vote.
3.38/5 (10 votes)
1 Apr 2014CPOL4 min read 128.2K   3.2K   21   8
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:

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

And here are example methods:

C#
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:

C#
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:

C#
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:

C#
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:

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

and three events that the code logic depends on:

C#
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:

C#
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]

C#
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:

C#
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:

Image 2

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

Image 3

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

Image 4

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:

Image 5

Points of Interest

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

C#
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:

C#
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:

C#
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. :)

License

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


Written By
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

 
QuestionCode examples missing Pin
stixoffire5-Jun-15 6:44
stixoffire5-Jun-15 6:44 
QuestionI can not run your code in VS2013 Pin
MTKNTS1-Feb-15 23:55
MTKNTS1-Feb-15 23:55 
AnswerRe: I can not run your code in VS2013 Pin
Abdallah Al-Dalleh2-Feb-15 6:56
Abdallah Al-Dalleh2-Feb-15 6:56 
AnswerRe: I can not run your code in VS2013 Pin
Member 1192846022-Aug-15 18:54
Member 1192846022-Aug-15 18:54 
QuestionNice work Pin
Emejulu JVT10-Apr-14 0:45
Emejulu JVT10-Apr-14 0:45 
AnswerRe: Nice work Pin
Abdallah Al-Dalleh10-Apr-14 1:55
Abdallah Al-Dalleh10-Apr-14 1:55 
GeneralMy vote of 2 Pin
leiyangge1-Apr-14 15:10
leiyangge1-Apr-14 15:10 
maybe too simple.
GeneralRe: My vote of 2 Pin
Abdallah Al-Dalleh1-Apr-14 19:53
Abdallah Al-Dalleh1-Apr-14 19:53 

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

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