Files
Hua.Todo/TodoList/Views/MainWindow.xaml.cs
T
2025-12-30 10:29:28 +08:00

63 lines
2.2 KiB
C#

using System.Windows;
using System.Windows.Input;
using TodoList.ViewModels;
namespace TodoList.Views
{
public partial class MainWindow : Window
{
public MainWindow(MainViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
this.Hide();
// Verify if app shuts down? No, ShutdownMode is Explicit.
}
private void ShortcutBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
e.Handled = true;
// Ignore modifier keys alone being the "main" key
if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl ||
e.Key == Key.LeftAlt || e.Key == Key.RightAlt ||
e.Key == Key.LeftShift || e.Key == Key.RightShift ||
e.Key == Key.LWin || e.Key == Key.RWin)
{
return;
}
var key = e.Key;
if (key == Key.System) key = e.SystemKey; // Handle Alt+Key
// Build modifier string
var modifiers = new System.Collections.Generic.List<string>();
if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) modifiers.Add("Control");
if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) modifiers.Add("Alt");
if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) modifiers.Add("Shift");
if ((Keyboard.Modifiers & ModifierKeys.Windows) == ModifierKeys.Windows) modifiers.Add("Windows");
// Map key to string
string keyStr = key.ToString();
// Simple mapping for letters/digits (A-Z, 0-9)
if (keyStr.Length == 2 && keyStr.StartsWith("D") && char.IsDigit(keyStr[1]))
{
keyStr = keyStr.Substring(1);
}
// Update ViewModel
if (DataContext is MainViewModel vm)
{
vm.ShortcutModifiers = string.Join(",", modifiers);
vm.ShortcutKey = keyStr;
}
}
}
}