动态格式字符串如何使用keydown

时间:2013-04-14 03:41:38

标签: c#

我希望在用户将值键入文本框时更改文本。

这样:

1 = 1
12 = (12) 
123 = (12) 3
1234 = (12) 34

我制作了这段代码:

private void txtFoneres_KeyDown(object sender, KeyEventArgs e)
{
    string p1 = e.KeyData.ToString();
    if (p1.StartsWith("D"))
    {
        p1 = p1.Replace("D", "");
    }
    if (p1.StartsWith("NumPad"))
    {
        p1 = p1.Replace("NumPad", "");
    }

    if (txtFoneres.TextLength == 1)
    {

        txtFoneres.Text = txtFoneres.Text + "(" + p1 + ")";
        txtFoneres.SelectionStart = 2;
        txtFoneres.SelectionLength = 2;
    }
}

使用我的代码,结果如下:

"1" = "1 
"12" = "1(2" (this is the problem, it would have to start with "("

有谁知道如何解决它并改变1(2为(12)?

1 个答案:

答案 0 :(得分:0)

我会尝试使用MaskedTextBox 使用一行代码,如

private void maskedTextBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (maskedTextBox1.Text.Length == 1)
    {
        maskedTextBox1.Mask = "(00) 00";
        maskedTextBox1.SelectionStart = 2;
    }
}