最近,看到網上經常會問如何進行窗口跳轉,大多數的問題都是牽扯到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函數,如下:
以下是引用片段: /// /// The main entry point for the application. /// [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類如下:
以下是引用片段: /// /// User info class /// 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 = ""; } } |