Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling VirtualKey in Windows 8 Store Apps with C#

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

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 '%'?

like image 846
joelc Avatar asked May 28 '13 04:05

joelc


2 Answers

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

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.

like image 116
joelc Avatar answered Sep 18 '22 20:09

joelc


You can't easily get this information from KeyUp because KeyUp only knows which keys are being pressed, not which letters are being typed. You could check for the shift key being down and you could also try to track caps lock yourself. Better you use TextChanged event.

like image 41
Farhan Ghumra Avatar answered Sep 19 '22 20:09

Farhan Ghumra