123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- 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<SystemID> 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
- {
- }
- }
- }
- }
|