I blocked all key on keyboard excluding 1-9 and I have a problem how to enable comma?
My code:
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;
}
This code will allow only numbers and comma
if (!char.IsDigit(e.KeyChar) && e.KeyChar != ',')
{
e.Handled = true;
}
Alternative
if ((e.KeyChar > (char)Keys.D9 || e.KeyChar < (char)Keys.D0) && e.KeyChar != ',')
{
e.Handled = true;
}
try this...
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;
}
}
根据虚拟密钥代码的文档,您需要OemComma,它是0xBC或(VirtualKey)188。
You can try this:
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();
}
First of all you have to remember that decimal mark ( either .
or ,
) has to be set up in the CultureInfo
. If you're planning to release your application to the further audience I would recommend keeping this in mind.
Another thing is that your condition makes no sense :
// 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
So proceeding with the code :
// 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
}
Remember that Windows.System.VirtualKey.Decimal
will not return the decimal mark ( separator ) based on the CultureInfo
but instead the decimal mark from the numpad.
If you want to use culture info ( international application ) you can find decimal mark in CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
and then compare the text input.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.