using AwInitilizer.Model; using PhihongEv.Lib; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Threading; namespace AwInitilizer { public class KeyinListener { public event EventHandler OnSystemIDReseived; private string stackedInput = string.Empty; private bool shiftPressed = false; private DispatcherTimer CleanInputTimer; private Window sourceWindow; public KeyinListener(Window sourceWindow) { this.sourceWindow = sourceWindow; sourceWindow.Closing += SourceWindow_Closing; sourceWindow.PreviewKeyDown += MainWindow_PreviewKeyDown; sourceWindow.PreviewKeyUp += MainWindow_PreviewKeyUp; CleanInputTimer = new DispatcherTimer(); CleanInputTimer.Interval = TimeSpan.FromSeconds(1); CleanInputTimer.Tick += CleanInputTimer_Tick; } private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.LeftShift || e.Key == Key.RightShift) { shiftPressed = true; return; } else if (e.Key == Key.Capital) { shiftPressed = !shiftPressed; return; } else if (e.Key == Key.Enter) { e.Handled = true; return; } else { if (e.Key >= Key.D0 && e.Key <= Key.D9) { // Number keys pressed so need to so special processing // also check if shift pressed var input = e.Key.ToString(); input = input.Remove(0, 1); stackedInput += input; } else if (e.Key == Key.OemMinus) { stackedInput += "-"; } else if (e.Key == Key.Return) { return; } else { var input = e.Key.ToString(); if (shiftPressed) input = input.ToUpper(); stackedInput += input; } } CleanInputTimer.Stop(); CleanInputTimer.Start(); } private void MainWindow_PreviewKeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.LeftShift || e.Key == Key.RightShift) { shiftPressed = false; } } private void CleanInputTimer_Tick(object sender, EventArgs e) { CleanInputTimer.Stop(); if (SystemID.TryLooseParse(stackedInput, out SystemID systemID)) { OnSystemIDReseived?.Invoke(this, systemID); //SystemIDScanReseived(systemID); } stackedInput = string.Empty; } private void SourceWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { try { sourceWindow.Closing -= SourceWindow_Closing; sourceWindow.PreviewKeyDown -= MainWindow_PreviewKeyDown; sourceWindow.PreviewKeyUp -= MainWindow_PreviewKeyUp; CleanInputTimer.Tick -= CleanInputTimer_Tick; CleanInputTimer.Stop(); } catch { } } } }