KeyPressEventArgs.KeyChar 属性

定义

获取或设置与按下的键对应的字符。

C#
public char KeyChar { get; }
C#
public char KeyChar { get; set; }

属性值

Char

撰写的 ASCII 字符。 例如,如果用户按下 Shift + K,则该属性返回一个大写的 K。

示例

以下示例创建一个 TextBox 控件。 该方法 keypressed 使用 KeyChar 属性检查 ENTER 键是否按下。 如果按下 ENTER 键,则会 Handled 将属性设置为 true,该属性指示事件已处理。

C#

using System;
using System.Windows.Forms;

public class Form1: Form
{
    public Form1()
    {
        // Create a TextBox control.
        TextBox tb = new TextBox();
        this.Controls.Add(tb);
        tb.KeyPress += new KeyPressEventHandler(keypressed);
    }

    private void keypressed(Object o, KeyPressEventArgs e)
    {
        // The keypressed method uses the KeyChar property to check 
        // whether the ENTER key is pressed. 

        // If the ENTER key is pressed, the Handled property is set to true, 
        // to indicate the event is handled.
        if (e.KeyChar == (char)Keys.Return)
        {
            e.Handled = true;
        }
    }

    public static void Main()
    {
        Application.Run(new Form1());
    }
}

注解

KeyChar使用属性在运行时对击键进行采样,并在特殊运行时情况下修改击键。 例如,当用户输入邮政编码时,可用于 KeyChar 禁用非数字键压缩,在数据输入字段中将所有字母键压更改为大写,或监视键盘或其他键输入设备以查找特定键组合。

可以获取或设置以下键:

  • a-z、A-Z。

  • CTRL。

  • 标点符号。

  • 数字键,同时位于键盘顶部和数字键盘上。

  • 进入。

无法获取或设置以下键:

  • TAB 键。

  • INSERT 和 DELETE。

  • 家。

  • 结束。

  • 向上页和向下页。

  • F1-F2。

  • ALT。

  • 箭头键。

备注

有关如何检测上述任何非字符键的信息,请参阅该 KeyEventArgs 类。

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
Windows Desktop 3.0, 3.1, 5, 6, 7

另请参阅