SelectKeyWindow.axaml.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using Avalonia.Controls;
  2. using Avalonia.Input;
  3. namespace SlamCross.Views;
  4. public partial class SelectKeyWindow : Window
  5. {
  6. public string? ChosenKey { get; private set; }
  7. public SelectKeyWindow() => InitializeComponent();
  8. private void KeyBox_KeyDown(object? sender, KeyEventArgs e)
  9. {
  10. ChosenKey = MapKey(e.Key);
  11. if (this.FindControl<TextBox>("KeyBox") is TextBox box)
  12. box.Text = ChosenKey;
  13. e.Handled = true;
  14. }
  15. private void OK_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
  16. {
  17. if (this.FindControl<TextBox>("KeyBox") is TextBox box && !string.IsNullOrWhiteSpace(box.Text))
  18. ChosenKey = box.Text.Trim().ToUpper();
  19. Close();
  20. }
  21. private void Cancel_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
  22. {
  23. ChosenKey = null;
  24. Close();
  25. }
  26. private static string MapKey(Key key) => key switch
  27. {
  28. >= Key.D0 and <= Key.D9 => ((char)('0' + (key - Key.D0))).ToString(),
  29. Key.F1 => "F1", Key.F2 => "F2", Key.F3 => "F3", Key.F4 => "F4",
  30. Key.F5 => "F5", Key.F6 => "F6", Key.F7 => "F7", Key.F8 => "F8",
  31. Key.F9 => "F9", Key.F10 => "F10", Key.F11 => "F11", Key.F12 => "F12",
  32. Key.Insert => "INS", Key.Delete => "DEL",
  33. Key.Home => "HOME", Key.End => "END",
  34. Key.PageUp => "PGUP", Key.PageDown => "PGDN",
  35. Key.NumPad0 => "KP_INS", Key.NumPad1 => "KP_END",
  36. Key.NumPad2 => "KP_DOWNARROW", Key.NumPad3 => "KP_PGDN",
  37. Key.NumPad4 => "KP_LEFTARROW", Key.NumPad5 => "KP_5",
  38. Key.NumPad6 => "KP_RIGHTARROW", Key.NumPad7 => "KP_HOME",
  39. Key.NumPad8 => "KP_UPARROW", Key.NumPad9 => "KP_PGUP",
  40. Key.Multiply => "KP_MULTIPLY", Key.Add => "KP_PLUS",
  41. Key.Subtract => "KP_MINUS", Key.Divide => "KP_SLASH",
  42. Key.OemMinus => "MINUS", Key.OemPlus => "EQUALS",
  43. Key.OemOpenBrackets => "LBRACKET", Key.OemCloseBrackets => "RBRACKET",
  44. Key.OemSemicolon => "SEMICOLON", Key.OemQuotes => "APOSTROPHE",
  45. Key.OemBackslash => "BACKSLASH", Key.OemComma => "COMMA",
  46. Key.OemPeriod => "PERIOD",
  47. _ => key.ToString().ToUpper()
  48. };
  49. }