在winform 界面編程中,我們有時候要在主界面打開之前先顯示登錄界面,當登錄界面用戶信息校驗正確后才打開主界面,而這時登陸界面也完成使命該功成身退了。
目前有兩種方法可實現:
方法1. 隱藏登錄界面
Program.cs 中代碼如下:
1
2
3
4
5
6
7
8
9
10
|
/// <summary> /// 應用程序的主入口點。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); Application.Run( new Login()); } |
Login.cs 中代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
/// <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 中代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/// <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 中代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
/// <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(); } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/Waming-zhen/p/6560886.html