【问题标题】:Event distinction by key with Return and Intro in WPFWPF中的Return和Intro按键区分事件
【发布时间】:2021-04-22 22:06:03
【问题描述】:

使用 Sap Business One,我意识到他们区分了介绍键(数字键盘)和输入/返回键。引发的事件会有所不同,具体取决于我按哪一个。这让我觉得我可以分别控制这两个事件。

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

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

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

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

【问题讨论】:

    标签: .net wpf .net-core keyboard


    【解决方案1】:

    有一个IsExtendedKey 属性被设置为true 用于数字小键盘Enter 键。

    它是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!");
            }
        }
    }
    

    【讨论】:

    • 有效!也可以将它用于 Home 或 End 键,但由于某种原因不能用于运算符或 Decimal。我想知道为什么这个属性是内部的而不是公开的。
    猜你喜欢
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2014-02-18
    相关资源
    最近更新 更多