在正常的"ENTER"和"ENTER"之间进行区分.和数字键盘"ENTER"按键? [英] Distinguish between normal "ENTER" and the number-pad "ENTER" keypress?

查看:291
本文介绍了在正常的"ENTER"和"ENTER"之间进行区分.和数字键盘"ENTER"按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my PreviewKeyDown() handler how do I tell the difference between the ENTER key on number-pad and the ENTER key on the main board?

两个键都为KeyEventArgs.Key返回相同的值Key.Enter.

Both keys return the same value Key.Enter for KeyEventArgs.Key.

对于这个问题,我可以找到最接近的答案:

The closest answer I can find to this question is here: What's the difference between Key.Enter and Key.Return?, but unfortunately this works only if the app is fully trusted.

我想要一个没有此限制的解决方案.

I'd like a solution without this restriction.

推荐答案

请参见

See link, example impl. below.

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)
  {
    if (AiLoggingService.IsErrorEnabled)
      AiLoggingService.LogError("Could not get the internal IsExtendedKey property from KeyEventArgs. Unable to detect numpad keypresses.", ex);
  }

  return false;
}

如果要检查常规的EnterKey,显然应该致电
e.Key == Key.Enter && !IsNumpadEnterKey(e)

N.b. if you want to check for regular EnterKey then obviously you should call
e.Key == Key.Enter && !IsNumpadEnterKey(e)

这篇关于在正常的"ENTER"和"ENTER"之间进行区分.和数字键盘"ENTER"按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆