maskedTextBox控件是使用掩碼區分正確的和不正確的用戶輸入的控件,掩碼定義如下
掩碼元素 |
說明 |
正則表達式元素 |
0 |
0 到 9 之間的任何一個數字。必選項。 |
\d |
9 |
數字或空格。可選項。 |
[ \d]? |
# |
數字或空格。可選項。如果此位置在掩碼中保留爲空,它將顯示爲空格。允許使用加號 (+) 和減號 (-)。 |
[ \d+-]? |
L |
ASCII 字母。必選項。 |
[a-zA-Z] |
? |
ASCII 字母。可選項。 |
[a-zA-Z]? |
& |
字符。必選項。 |
[\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}] |
C |
字符。可選項。 |
[\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}]? |
A |
字母數字。可選項。 |
\W |
. |
相應於區域性的小數點佔位符。 |
不可用。 |
, |
相應於區域性的千分位佔位符。 |
不可用。 |
: |
相應於區域性的時間分隔符。 |
不可用。 |
/ |
相應於區域性的日期分隔符。 |
不可用。 |
$ |
相應於區域性的貨幣符號。 |
不可用。 |
< |
將後面的所有字符轉換爲小寫。 |
不可用。 |
> |
將後面的所有字符轉換爲大寫。 |
不可用。 |
| |
停止前面的大寫轉換或小寫轉換。 |
不可用。 |
\ |
對掩碼字符進行轉義,將它轉換爲原義字符。“\\”是反斜槓的轉義序列。 |
\ |
所有其他字符。 |
原義字符。所有非掩碼元素將在 MaskedTextBox 中以原樣顯示。 |
所有其他字符。 |
使用起來比較簡單,但是要實現實際的效果,感覺並不方便,下面我們一起看下如何使用
1.界面佈局
界面佈局很簡單,這裏就不細講了,需要注意的是,這裏我們設置的掩碼是8個0,用來驗證密碼是8位數字
2.用法示例
在寫代碼之前,我們需要注意兩個屬性
一個是PasswordChar,這個屬性可以讓我們的密碼以另外的形式顯示出來,比如#
另一個是PromptChar,這個屬性可以改變默認的掩碼形式,這裏我們改成空格
具體的代碼實現如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//maskedTextBox1.Mask = "00/00/0000";
maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected);
maskedTextBox1.Text = "";
}
void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
if (maskedTextBox1.MaskFull)
{
toolTip1.ToolTipTitle = "Input Rejected - Too Much Data";
toolTip1.Show("You cannot enter any more data into the date field. Delete some characters in order to insert more data.", maskedTextBox1, 0, -20, 5000);
}
else if (e.Position == maskedTextBox1.Mask.Length)
{
toolTip1.ToolTipTitle = "Input Rejected - End of Field";
toolTip1.Show("You cannot add extra characters to the end of this date field.", maskedTextBox1, 0, -20, 5000);
}
else
{
toolTip1.ToolTipTitle = "Input Rejected";
toolTip1.Show("You can only add numeric characters (0-9) into this date field.", maskedTextBox1, 0, -20, 5000);
}
}
private void maskedTextBox1_Validated(object sender, EventArgs e)
{
if (maskedTextBox1.Text.Equals("12345678"))
{
MessageBox.Show("驗證成功");
}
else
{
MessageBox.Show("密碼錯誤");
}
maskedTextBox1.Text = "";
}
void maskedTextBox1_KeyDown(object sender, KeyEventArgs e)
{
// The balloon tip is visible for five seconds; if the user types any data before it disappears, collapse it ourselves.
toolTip1.Hide(maskedTextBox1);
}
}
}