c# Tutorial : How write a password protected application

In this tutorial i will show you what can we write an application that protected with username and password. Let's start.

First we make a project.
Then we make the design of the loging form.(we required 2 textbox that called txtUser,and txtPass, 1 checkbox, 1 button that I called btnLogin and some label.)
That's mine : 
Posted Image
then we can start the designing of the main form( the main form we can see after logging in)

The code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace password_protect_application{
       
public partial class Form1 : Form
       
{
               
Form2 mainform = new Form2();
               
public Form1()
               
{
                       
InitializeComponent();
               
}

               
private void Form1_Load(object sender, EventArgs e)
               
{
               
}
               
private void btnLogin_Click(object sender, EventArgs e)
               
{
                       
//the checking method
                       
//you can put into the bracket the password,and username what you want
                       
if (txtUser.Text.ToString().CompareTo("test") == 0 & txtPass.Text.ToString().CompareTo("test") == 0)
                       
{
                               
MessageBox.Show("Login Sucessfull.Click OK to continue", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
                               
this.Hide();     //hide the login form
                                mainform
.Show(); //& show the main form
                       
}
                       
else
                       
{
                               
MessageBox.Show("Wrong Username/Password! n Please try again!", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                txtPass
.Text = ""; //delete writed password
         
                      txtUser
.Text = ""; //delete writed username
                       
}
               
}

               
private void checkBox1_CheckedChanged(object sender, EventArgs e)
               
{
                       
if (checkBox1.Checked == true)
                       
{
                                txtPass
.PasswordChar = '*'; //set passwordchar to '*'
                                checkBox1
.Text = "Show password"; //change checkbox text to show password
                       
}
                       
else
                       
{
                                txtPass
.PasswordChar = (char)0; //reset passwordchar to default
                                checkBox1
.Text = "Hide password"; //change password to hide password
                       
}
               
}

       
}
}

This source code content a password hide/show function also :
)


No comments:

Post a Comment