作者tag:windows/.net 新手入門(c#) CSDN 推薦tag:c#
上一篇: 如何動態調用DLL中類的方法以及屬性 | 下一篇: 如何在C#去求矩陣的逆矩陣
如何用C#寫一個簡單的Login視窗
最近,看到網上經常會問如何進行視窗跳轉,大多數的問題都是牽扯到Login視窗。其實,在Visual Studio 6以來,比較正確的做法,是判斷Login視窗的傳回值,然後決定是否開啟主表單,那麼在C#中也是一樣的。
具體做法如下:
首先,建立Login視窗,然後添加相應的輸入框和按鈕,設定視窗的AcceptButton為表單的確認按鈕,而CancelButton為表單的取消按鈕。例如:
this.AcceptButton = this.btnOK;
this.CancelButton = this.btnCancel;
定義確定按鈕以及取消按鈕事件,如下:
private void btnOK_Click(object sender, System.EventArgs e)
{
// Here is to use fixed username and password
// You can check username and password from DB
if( txtUserName.Text == "Admin" && txtPassword.Text == "nopassword" )
{
// Save login user info
uiLogin.UserName = txtUserName.Text;
uiLogin.Password = txtPassword.Text;
// Set dialog result with OK
this.DialogResult = DialogResult.OK;
}
else
{
// Wrong username or password
nLoginCount++;
if( nLoginCount == MAX_LOGIN_COUNT )
// Over 3 times
this.DialogResult = DialogResult.Cancel;
else
{
MessageBox.Show( "Invalid user name and password!" );
txtUserName.Focus();
}
}
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
// Set dialog result with Cancel
this.DialogResult = DialogResult.Cancel;
}
然後,在Login表單的Closing事件中,要進行處理,如下:
private void frmLogin_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Check whether form is closed with dialog result
if( this.DialogResult != DialogResult.Cancel &&
this.DialogResult != DialogResult.OK )
e.Cancel = true;
}
除此外,Login表單一些輔助代碼如下:
private int nLoginCount = 0;
private const int MAX_LOGIN_COUNT = 3;
private UserInfo uiLogin;
public frmLogin( ref UserInfo ui )
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
// Set login info to class member
uiLogin = ui;
}
調用的時候,要修改程式的Main函數,如下:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static voidMain()
{
UserInfo ui = new UserInfo();
frmLogin myLogin = new frmLogin( ref ui );
if( myLogin.ShowDialog() == DialogResult.OK )
{
//Open your main form here
MessageBox.Show( "Logged in successfully!" );
}
else
{
MessageBox.Show( "Failed to logged in!" );
}
}
而附加的UserInfo類如下:
/// <summary>
/// User info class
/// </summary>
public class UserInfo
{
private string strUserName;
private string strPassword;
public string UserName
{
get{ return strUserName;}
set{ strUserName = value; }
}
public string Password
{
get{ return strPassword;}
set{ strPassword = value;}
}
public UserInfo()
{
strUserName = "";
strPassword = "";
}
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=652394