【问题标题】:Distinguish between normal "ENTER" and the number-pad "ENTER" keypress?区分普通的“ENTER”和数字键盘的“ENTER”键?
【发布时间】:2011-12-24 22:36:51
【问题描述】:

在我的PreviewKeyDown() 处理程序中,我如何区分数字键盘上的 ENTER 键和主板上的 ENTER 键?

对于KeyEventArgs.Key,两个键返回相同的值Key.Enter

我能找到的最接近这个问题的答案是:What's the difference between Key.Enter and Key.Return?,但不幸的是,这只有在应用程序完全受信任的情况下才有效。

我想要一个没有这个限制的解决方案。

【问题讨论】:

  • 可能没有 :( 虽然看起来只有部分信任就足够了?

标签: wpf keyboard keyboard-events


【解决方案1】:

请参阅link,示例 impl。下面。

private static bool IsNumpadEnterKey(KeyEventArgs e)
{
  if (e.Key != Key.Enter)
    return false;

  // To understand the following UGLY implementation please check this MSDN link. Suggested workaround to differentiate between the Return key and Enter key.
  // https://social.msdn.microsoft.com/Forums/vstudio/en-US/b59e38f1-38a1-4da9-97ab-c9a648e60af5/whats-the-difference-between-keyenter-and-keyreturn?forum=wpf
  try
  {
    return (bool)typeof(KeyEventArgs).InvokeMember("IsExtendedKey", BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance, null, e, null);
  }
  catch (Exception ex)
  {
    Log("Could not get the internal IsExtendedKey property from KeyEventArgs. Unable to detect numpad keypresses.", ex);
  }

  return false;
}

注意如果您想检查常规的 EnterKey,那么显然您应该致电
e.Key == Key.Enter && !IsNumpadEnterKey(e)

【讨论】:

    【解决方案2】:

    每个键的扫描码都不同。您必须能够看到这一点。

    【讨论】:

    • 两个键返回相同的值 Key.Enter 用于 KeyEventArgs.Key。
    【解决方案3】:

    对不起,如果我没用,但我认为这是不可能的。两个 ENTER 键返回相同的内容,因此没有真正的区分方法。

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2011-08-30
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      相关资源
      最近更新 更多