using System; using System.Collections.Specialized; using System.Globalization; using System.Windows; using System.Windows.Data; using System.Windows.Interop; using PersonalToolBox.Helpers; using PersonalToolBox.ViewModels; namespace PersonalToolBox.Views; public partial class MainWindow : Window { private readonly MainViewModel _viewModel; private readonly HotKeyManager _hotKeyManager; public MainWindow(MainViewModel viewModel, HotKeyManager hotKeyManager) { InitializeComponent(); _viewModel = viewModel; _hotKeyManager = hotKeyManager; DataContext = viewModel; viewModel.Logs.CollectionChanged += OnLogsCollectionChanged; } /// /// 窗口句柄就绪后注册全局快捷键 /// protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); var hwndSource = (HwndSource)PresentationSource.FromVisual(this)!; _hotKeyManager.Initialize(hwndSource.Handle); // 挂载 WndProc 钩子,拦截 WM_HOTKEY 消息 hwndSource.AddHook(WndProcHook); // 注册所有已配置快捷键的工具 _viewModel.RegisterAllHotKeys(); } /// /// 窗口消息钩子 /// private IntPtr WndProcHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { handled = _hotKeyManager.TryHandleMessage(msg, wParam, lParam); return IntPtr.Zero; } private void OnLogsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add && LogListBox.Items.Count > 0) { Dispatcher.BeginInvoke(new Action(() => { LogListBox.ScrollIntoView(LogListBox.Items[^1]); }), System.Windows.Threading.DispatcherPriority.Background); } } } /// /// bool → double: true=1.0, false=0.4 (工具卡片失效时置灰) /// public class BoolToOpacityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value is bool b && b ? 1.0 : 0.4; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException(); } /// /// string → string: 取字符串首字符作为图标占位 /// public class FirstCharConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var s = value as string; return string.IsNullOrEmpty(s) ? "?" : s[0].ToString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException(); }