//以下是抽象类,主要是看着内部只有逻辑的代码出现了Keys这种很具体的类型,不爽。说不定会用作别的。using System.Collections.Generic; namespace KeyboardSynchronizer { public abstract class FuncQueue<T> { public bool Adding { get; private set; } private T toggler; public int Id { get; private set; } public int Index { get; private set; } = -1; public List<T> Parameters { get; } = new List<T>(); protected abstract T Empty { get; } /// <summary> /// Insert these to stop adding more parameters and reset this instance. /// </summary> public T[] Restarter { get; set; } protected abstract bool IsIndexElement(T t); protected abstract int CreateNewIndex(T t); protected abstract bool Equals(T a, T b); public void Insert(T t) { if (Equals(t, Empty)) { return; } if (IsIndexElement(t)) { if (Adding) { add(t); } else { Index = CreateNewIndex(t); } } else { if (Equals(toggler, Empty)) { toggler = t; } else if (Equals(toggler, t)) { if (Adding) { add(t); } else { if (Index == -1) { Id++; } else { Adding = true; } } } else { if (Adding) { add(t); } else { toggler = t; Id = 0; Index = -1; } } } } private void add(T t) { if (Restarter != null && Restarter.Length > 0 && Parameters.Count + 1 >= Restarter.Length && Equals(Restarter[Restarter.Length - 1], t)) { var i = Parameters.Count - 1; var j = Restarter.Length - 2; for (; i >= 0 && j >= 0;) { if (Equals(Parameters[i], Restarter[j])) { i--; j--; continue; } Parameters.Add(t); return; } Adding = false; Id = 0; toggler = Empty; Index = -1; Parameters.Clear(); } else { Parameters.Add(t); } } } }//以下是实现类,用于自定义快捷键,先按下一个键X一次或多次,用于区分不同功能,然后按一些数字,指定第一个参数,再次按X,结束指定第一个参数,并开始输入更多参数。
using System.Linq; using System.Windows.Forms; namespace KeyboardSynchronizer { public class KeysQueue : FuncQueue<Keys> { static Keys[] numbers = { Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9 }; public KeysQueue(){ Restarter = new[] { Keys.S, Keys.T, Keys.O, Keys.P }; } protected override Keys Empty { get { return Keys.None; } } protected override bool Equals(Keys a, Keys b) { return a == b; } protected override int CreateNewIndex(Keys t) { var v = (Index > -1 ? Index.ToString() : string.Empty) + t.ToString()[1]; try { return int.Parse(v); } catch { return Index; } } protected override bool IsIndexElement(Keys t) { return numbers.Contains(t); } } }
时间: 2024-10-10 06:32:43