gpt4 book ai didi

c# - 为什么用于 Delete 的 KeyChar 返回与 Period 相同的值?

转载 作者:太空狗 更新时间:2023-10-30 00:12:57 25 4
gpt4 key购买 nike

我正在捕获一个 KeyPress-Event 来检查某些类型的允许值。为了能够删除,我在实际检查之前使用了以下代码

if (e.KeyChar == (char)Keys.Delete || e.KeyChar == (char)Keys.Back)
{
return;
}
...actual check for only digits or whatever

问题是当我在键盘上按下句号时,e.KeyChar == (char)Keys.Delete 也是如此。

这怎么可能?我能做些什么呢?

谢谢

最佳答案

来自 MSDN documentation on the Keys enumeration :

The Keys class contains constants for processing keyboard input. The members of the Keys enumeration consist of a key code and a set of modifiers combined into a single integer value. In the Win32 application programming interface (API) a key value has two halves, with the high-order bits containing the key code (which is the same as a Windows virtual key code), and the low-order bits representing key modifiers such as the SHIFT, CONTROL, and ALT keys.

将这些常量转换为 char 是没有意义的,因为您将丢失有值(value)的信息,而且常量值不对应 ASCII 字符代码。

来自 MSDN concerning the KeyChar property of KeyPressEventArgs :

You cannot get or set the following keys (...) INSERT and DELETE (...)

KeyChar 返回对应于按下的键的 char 值(ASCII 字符代码),而不是其(原始)键代码。因此,您无法检测到各种特殊键,也无法将值与 Keys 枚举常量进行比较。

改用 KeyEventArgsKeyCode 属性。由于它是 Keys 类型,而不是 char 类型,因此非常适合您的目的。为了访问此信息,您必须处理 KeyDown 事件而不是 KeyPress 事件。

顺便说一句,根据MSDN page on the Control KeyPress event , 对于非字符键根本不会引发此事件:

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

关于c# - 为什么用于 Delete 的 KeyChar 返回与 Period 相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1504754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com