C# winform 主界面打開並關閉登錄界面
阿新 • • 發佈:2018-05-19
lose AI ID cancel 信息 message 技術 else ()
在winform 界面編程中,我們有時候要在主界面打開之前先顯示登錄界面,當登錄界面用戶信息校驗正確後才打開主界面,而這時登陸界面也完成使命該功成身退了。
目前有兩種方法可實現:
方法1. 隱藏登錄界面
Program.cs 中代碼如下:
/// <summary> /// 應用程序的主入口點。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Login()); }
Login.cs 中代碼如下:
/// <summary> /// login /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnLogin_Click(object sender, EventArgs e) { if (txtPassword.Text == "12345678") { UI ui = new UI(); this.Visible = false; ui.ShowDialog();//此處不可用Show() this.Dispose(); this.Close(); } else { MessageBox.Show("Password is incorrect ", "Prompt message",MessageBoxButtons.OK,MessageBoxIcon.Error); } } /// <summary> /// exit /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnExit_Click(object sender, EventArgs e) { this.Dispose(); this.Close(); }
方法2. 登錄界面以 dialog形式打開,返回登錄結果
Program.cs 中代碼如下:
/// <summary> /// 應用程序的主入口點。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Login login = new Login(); login.ShowDialog(); if (login.DialogResult == DialogResult.OK) { login.Dispose(); Application.Run(new UI()); } else if (login.DialogResult == DialogResult.Cancel) { login.Dispose(); return; } }
Login.cs 中代碼如下:
/// <summary> /// login /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnLogin_Click(object sender, EventArgs e) { if (txtPassword.Text == "12345678") { this.DialogResult = DialogResult.OK; this.Dispose(); this.Close(); } else { MessageBox.Show("Password is incorrect ", "Prompt message",MessageBoxButtons.OK,MessageBoxIcon.Error); } } /// <summary> /// exit /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnExit_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Dispose(); this.Close(); }
C# winform 主界面打開並關閉登錄界面