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);
}
}
}