KeyDown C#中只允许使用逗号

时间:2017-03-09 11:15:32

标签: c# uwp

我阻止了键盘上的所有键,不包括1-9,我有一个问题如何启用逗号?

我的代码:

private void textbox_KeyDown(object sender, KeyRoutedEventArgs e)
    if (e.Key >= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9 || e.Key >= Windows.System.VirtualKey.NumberPad0 && e.Key <= Windows.System.VirtualKey.NumberPad9 || e.Key == Windows.System.VirtualKey.Decimal)
    {
    e.handled = false;
    }
    else 
    {
    e.handled = true;
    }

5 个答案:

答案 0 :(得分:0)

此代码仅允许数字和逗号

if (!char.IsDigit(e.KeyChar) && e.KeyChar != ',')
{
    e.Handled = true;
}

替代

 if ((e.KeyChar > (char)Keys.D9 || e.KeyChar < (char)Keys.D0) && e.KeyChar != ',')
{ 
    e.Handled = true; 
}

答案 1 :(得分:0)

试试这个......

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if((e.KeyChar >= 48 && e.KeyChar <= 57) || (e.KeyChar >= 97 && e.KeyChar <= 105))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

答案 2 :(得分:0)

根据Virtual Key Codes的文档,您需要OemComma,即0xBC或(VirtualKey)188。

答案 3 :(得分:0)

你可以试试这个:

        string keyInput = e.KeyChar.ToString();

        if (Char.IsDigit(e.KeyChar))
        {
            // Digits are OK
        }
        else if (e.KeyChar == '\b')
        {
            // Backspace key is OK
        }
        else if (e.KeyChar == ',')
        {
            // Comma key is OK
        }


        else
        {
            // Swallow this invalid key and beep
            e.Handled = true;
            //    MessageBeep();
        }

答案 4 :(得分:0)

首先,您必须记住必须在.中设置小数点(,CultureInfo)。如果您计划向更多受众群体发布您的申请,我建议您牢记这一点。

另一件事是你的情况毫无意义:

// this has to be always true
e.Key >= Windows.System.VirtualKey.Number0 
&& 
e.Key <= Windows.System.VirtualKey.Number9 
|| // above or below has to be true
e.Key >= Windows.System.VirtualKey.NumberPad0 
&& // something from above has to be true and below has to be true
e.Key <= Windows.System.VirtualKey.NumberPad9 
|| // or just decimal mark .. ?
e.Key == Windows.System.VirtualKey.Decimal

继续执行代码:

// check for the keys 
if(
    ( // if numeric between 0 and 9
        e.Key >= Windows.System.VirtualKey.Number0 
        &&
        e.Key <= Windows.System.VirtualKey.Number9
    ) 
    || // or
    ( // numeric from numpad between 0 and 9
        e.Key >= Windows.System.VirtualKey.NumberPad0
        &&
        e.Key <= Windows.System.VirtualKey.NumberPad9 
    )
    || // or decimal mark
    e.Key == Windows.System.VirtualKey.Decimal
)
{
    // your logic
}

请记住,Windows.System.VirtualKey.Decimal不会根据CultureInfo返回小数点(分隔符),而是返回小键盘中的小数点。

如果您想使用文化信息(国际申请),您可以在CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator中找到小数点,然后比较文字输入。