//需要有调用窗体注册:KeyDown事件且属性:KeyPreview=true
#region 条件处理 BarCodeHook barCodeHook = null; private void MIE_MainFrom_KeyDown(object sender, KeyEventArgs e) { if (barCodeHook == null) { barCodeHook = new BarCodeHook(); barCodeHook.ResolveBarCodeCompletedEvent += new BarCodeHook.ResolveBarCodeCompleted(barCodeHook_ResolveBarCodeCompletedEvent); } barCodeHook.AppendBarCode = e.KeyValue; } void barCodeHook_ResolveBarCodeCompletedEvent(BarCodeHook barCodeHook) { //自己的条码处理方法
} #endregion 条件处理
View Code
public class BarCodeHook { /// <summary> /// 条形码实例 /// </summary> BarCodes barCode; /// <summary> /// 单据编号 /// </summary> public delegate void ResolveBarCodeCompleted(BarCodeHook barCodeHook); public event ResolveBarCodeCompleted ResolveBarCodeCompletedEvent; /// <summary> /// 构造函数 /// </summary> public BarCodeHook() { //初始化条码事件 this.barCode = new BarCodes(); // 添加条码扫描完成事件 this.barCode.BarCodeCompletedEvent += new BarCodes.BarCodeCompleted(barCode_BarCodeCompletedEvent); } /// <summary> /// 添加条码扫描完成触发事件 /// </summary> /// <param name="barCode"></param> private void barCode_BarCodeCompletedEvent(string barCode) { if (barCode == null || barCode == "") return; ResolveBarCode(barCode.ToLower()); } /// <summary> /// 条码编号处理 /// </summary> private void ResolveBarCode(string barCode) { this.ResolveBarCodeCompletedEvent(this); } /// <summary> /// 逐个添加字符 /// </summary> public int AppendBarCode { set { barCode.AppendBarCode(value); } } /// <summary> /// 条形码 /// </summary> private struct BarCodes { public int VirtKey; //虚拟码 public int ScanCode; //扫描码 public int KeyValue; //键名 public uint AscII; //AscII public char Chr; //字符 public string BarCode; //条码信息 public bool IsValid; //条码是否有效 public DateTime Time; //扫描时间 /// <summary> /// 条件读取完毕触发的事件 /// </summary> /// <param name="barCode"></param> public delegate void BarCodeCompleted(string barCode); public event BarCodeCompleted BarCodeCompletedEvent; /// <summary> /// 逐个添加字符 /// </summary> /// <param name="keyValue">当前字符</param> public void AppendBarCode(int keyValue) { if (keyValue == 16) return; if ((DateTime.Now.Ticks - this.Time.Ticks) > 800000) { this.BarCode = ""; } this.KeyValue = keyValue; this.BarCode += (char)keyValue; this.Time = DateTime.Now; if (KeyValue == 13 && this.BarCode.Length > 3)//回车键&&条件长度大于3 { this.IsValid = true; if (this.BarCodeCompletedEvent != null) BarCodeCompletedEvent(this.BarCode); } } } }