Distinguish between normal “ENTER” and the number-pad “ENTER” keypress?

别说谁变了你拦得住时间么 提交于 2019-12-19 07:49:22

问题


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?

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.


回答1:


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;
}

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




回答2:


Sorry if I am being useless, but I don't think this is possible. Both of the ENTER keys return the same thing, so there is no real way to distinguish.




回答3:


The scan code is different for every key. You will have to be able to see that.



来源:https://stackoverflow.com/questions/8059177/distinguish-between-normal-enter-and-the-number-pad-enter-keypress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!