1 //限定用戶名必須為字母
2 private void txtName_KeyPress(object sender, KeyPressEventArgs e)
3 {
4 if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z'))
5 {
6 e.Handled = false;
7 }
8 else {
9 MessageBox.Show("用戶名只能為字母!");
10 e.Handled = true;
11 }
12 }
2.光標進入文本框時背景藍色,文字白色;光標離開文本框時,背景白色,文字黑色。 界面:
1 //光標進入文本框時,背景為藍色,字體為白色;
2 //光標離開文本框時,背景為白色,字體為黑色。
3 private void txtName_Enter(object sender, EventArgs e)
4 {
5 txtName.ForeColor = Color.White;
6 txtName.BackColor = Color.Blue;
7 }
8
9 private void txtName_Leave(object sender, EventArgs e)
10 {
11 txtName.BackColor = Color.White;
12 txtName.ForeColor = Color.Black;
13 }
3.當輸入用戶名“admin”和密碼“123”之後,單擊”確定“按鈕,系統將彈出消息框以顯示輸入正確,否則顯示用戶名或密碼錯誤的提示信息。
1 private void btnLogin_Click(object sender, EventArgs e)
2 {
3 string userName = txtName.Text;
4 string password = txtPwd.Text;
5 if (userName == "admin" && password == "123")
6 {
7 MessageBox.Show("歡迎進入個人理帳系統!", "登陸成功!", MessageBoxButtons.OK, MessageBoxIcon.Information);
8 }
9 else
10 {
11 MessageBox.Show("您輸入的用戶名或密碼錯誤!", "登錄失敗!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
12 }
13 }
4.單擊”取消“按鈕,清除輸入信息,並將光標定位在txtName文本框中。
1 private void btnCancel_Click(object sender, EventArgs e)
2 {
3 txtName.Text = "";
4 txtPwd.Text = "";
5 txtName.Focus();
6 }
5.最終界面:

小技巧:為label設置Image屬性,為了讓圖片完整顯示出來,需要把label的AutoSize屬性設置為false,然後適當拉大label大小。還要注意,ImageAlign屬性設置為MiddleLeft,TextAlign屬性設置為MiddleRight。
Notice:
(1)ico:是Windows的圖標文件格式的一種,可以存儲單個圖案、多尺寸、多色板的圖標文件。 (2)MessageBox:消息框,顯示一個模態對話框,其中包含一個系統圖標、 一組按鈕和一個簡短的特定於應用程序消息,如狀態或錯誤的信息。 (3)Button的快捷鍵通過設置Text屬性為”取消(&C)“實現。 (4)此練習使用的軟件為Visual Studio 2012,圖形資源由VS提供,據說在VS的安裝文件夾Common7\ImageLibrary中能找到,沒有的話,可以到官網下載。