看到網上經常會問如何進行窗口跳轉,大多數的問題都是牽扯到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;
this.dialogresult = dialogresult.ok;
}
else
{
nlogincount++;
if( nlogincount == max_login_count )
this.dialogresult = dialogresult.cancel;
else
{
messagebox.show( "invalid user name and password!" );
txtusername.focus();
}
}
}
private void btncancel_click(object sender, system.eventargs e)
{
this.dialogresult = dialogresult.cancel;
}
然后,在login窗體的closing事件中,要進行處理,如下:
private void frmlogin_closing(object sender, system.componentmodel.canceleventargs e)
{
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 void main()
{
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 = "";
}
}
,歡迎訪問網頁設計愛好者web開發。
新聞熱點
疑難解答