在 WPF 中使用 Return 和 Intro 按键区分事件

Event distinction by key with Return and Intro in WPF

使用 Sap Business One,我意识到他们区分了介绍键(数字键盘)和 enter/return 键。引发的事件因我按的事件而异。这让我觉得我可以分别控制这两个事件。

在 C# 中,我可以使用此方法设置按键事件:

static void KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        // my code here
        e.Handled = true;
    }
}

唯一的问题是无论按哪个键,我得到的结果都是一样的。对于 Key 枚举,有两个值,Enter 和 Return,它们都具有相同的值:6。我尝试检查 KeyEventArgs 的每个 属性,但我找不到任何区别。

是否可以知道用户按下了哪个键?

数字小键盘 Enter 键的 IsExtendedKey 属性 设置为 true

虽然是 internal,所以你必须使用反射来获取它的值:

static void KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        PropertyInfo pi = typeof(KeyEventArgs)
            .GetProperty("IsExtendedKey", BindingFlags.NonPublic | BindingFlags.Instance);
        if (pi != null && (bool)pi.GetValue(e) == true)
        {
            MessageBox.Show("Into key was pressed!");
        }
        else
        {
            MessageBox.Show("Enter key was pressed!");
        }
    }
}