使用 C# 处理 Windows 8 商店应用程序中的 VirtualKey应用程序、商店、Windows、VirtualKey

2023-09-06 06:41:54 作者:願得一人心

我知道如何处理关键事件,即

I'm aware of how to handle key events, i.e.

private void Page_KeyUp(object sender, KeyRoutedEventArgs e)
{
  switch (e.Key)
  {
    case Windows.System.VirtualKey.Enter:
      // handler for enter key
      break;

    case Windows.System.VirtualKey.A:
      // handler for A key
      break;

    default:
      break;
  }
}

但是如果我需要区分小写a"和大写A"怎么办?另外,如果我想处理百分号%"之类的键怎么办?

But what if I need to discern between lower-case 'a' and upper-case 'A'? Also, what if I want to handle keys like the percent sign '%'?

推荐答案

在别处得到了答案.有兴趣的朋友...

Got an answer elsewhere. For those that are interested...

public Foo()
{
    this.InitializeComponent();
    Window.Current.CoreWindow.CharacterReceived += KeyPress;
}

void KeyPress(CoreWindow sender, CharacterReceivedEventArgs args)
{
    args.Handled = true;
    Debug.WriteLine("KeyPress " + Convert.ToChar(args.KeyCode));
    return;
}

更好的是,将 Window.Current.CoreWindow.CharacterReceived += KeyPress; 移动到 GotFocus 事件处理程序中,并添加 Window.Current.CoreWindow.CharacterReceived -= KeyPress;代码> 到 LostFocus 事件处理程序中.

Even better, move the Window.Current.CoreWindow.CharacterReceived += KeyPress; into a GotFocus event handler, and add Window.Current.CoreWindow.CharacterReceived -= KeyPress; into a LostFocus event handler.