如何检测 KeyDown 事件中的 NumberDecimalSeparator (C#)
我试图查看用户是否在文本框中按下了小数分隔符,并根据其他参数允许或禁止它。
NumberdecimalSeparator 返回 46 或“.” 在我的美国系统上。 许多其他国家/地区使用“,”作为分隔符。 当我按下句号时,KeyDown 事件将 KeyValue 设置为 190。
我是否只是继续寻找逗号/句号,还是有更好的方法?
I'm trying to see if the user has pressed a decimal separator in a text box, and either allow or suppress it depending on other parameters.
The NumberdecimalSeparator returns as 46, or '.' on my US system. Many other countries use ',' as the separator. The KeyDown event sets the KeyValue to 190 when I press the period.
Do I just continue to look for commas/periods, or is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该调用
获取当前用户界面区域性的小数点分隔符。 您可以使用其他文化来获取其他语言的分隔符。
编辑
从我的系统中报告的 166 种文化 (
CultureInfo.GetCultures(CultureTypes.SpecificCultures).Count()
) 来看,似乎只使用了两个分隔符:句点和逗号。 您可以在您的系统中尝试此操作:假设这是真的,此方法可能会有所帮助(请注意,
keyCode
与modifiers
标志进行 OR 运算,以便消除无效组合):最后一点:根据 按键枚举,您提到的值46对应于DEL(删除)键(即Num Lock关闭时的点)。
The call
gets the decimal separator for the current user interface culture. You can use other cultures to get the separator for other languages.
EDIT
From the 166 cultures that are reported in my system (
CultureInfo.GetCultures(CultureTypes.SpecificCultures).Count()
), it seems that only two separators are used: period and comma. You can try this in your system:Assuming that this is true, this method may be helpful (note that the
keyCode
is OR'ed with themodifiers
flag in order to eliminate invalid combinations):A last note: According to Keys enumeration, the value 46 that you mention corresponds to the DEL (Delete) key (i.e. the point when Num Lock is OFF).
这里的问题是
KeyEventArgs
中的值是按键代码,而不是字符。 如果您改为处理KeyPress
,您将在KeyPressEventArgs
中获得一个可用于比较的字符。注意:您确实应该比较
NumberDecimalSeparator
字符,因为它是一个字符串,而不是单个字符,因此您需要考虑字符串中存在多个字符的情况。The problem here is that the values in the
KeyEventArgs
are key codes, not characters. If you handleKeyPress
instead, you will get a char in theKeyPressEventArgs
which you can use for the comparison.Note: You should really compare the
NumberDecimalSeparator
characters as it is a string, not a single character so you need to consider scenarios where there is more than one character in the string.如果您需要知道按下的字符是否是小数分隔符:
但是,如果您需要接受小数数字键盘键作为任何区域性的小数分隔符:
If you need know if the char pressed is decimal separator:
But, if you need acept decimal numpad key as decimal separator of any culture: