WinForm中TextBox 中判断扫描枪输入与键盘输入

本文转载:http://www.cnblogs.com/Hdsome/archive/2011/10/28/2227712.html

 提出问题:在收货系统中,常常要用到扫描枪扫描条码输入到TextBox,当条码无法扫描时,需要手工输入。如果是扫描枪输入时,我们将自动去判读条码,而手工输入时,最终需要加按回车键确认后判读条码。这时候我们就要判断输入设备是手工还是扫描枪。

     尝试的方法:

     1.将TextBox属性设为ReadOnly=true。结果:无法输入。

     2.在TextBox的KeyPress事件中设置属性e.handle=true。结果:扫描枪输入时也会触发KeyPress事件,因此也不能输入。

     3.在TextBox的ValueChanged事件中判断结果。结果:扫描枪也是一个一个字符输入,不是一次性将整个条码输入。

     思考:扫描枪其实在输入上与键盘完全相似。但是人工输入和扫描设备输入的区别在于,扫描设备输入速度比较快而且时间间隔比较平均。

     实验:

     

     实验结果证明开始的推断。

     解决方法:

        Private DateTime _dt = DateTime.Now;  //定义一个成员函数用于保存每次的时间点
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            DateTime tempDt = DateTime.Now;          //保存按键按下时刻的时间点
            TimeSpan ts = tempDt .Subtract(_dt);     //获取时间间隔
            if (ts.Milliseconds > 50)                           //判断时间间隔,如果时间间隔大于50毫秒,则将TextBox清空
                textBox1.Text = "";
            dt = tempDt ;
        }

       至此, 问题解决,希望大家有更好的方法留言交流

本文在实际项目中使用;

DateTime dtStart = DateTime.Now;
            this.txtCustomerNo.TbKeyPress += (sender, e) =>
            {
                DateTime dtCurrent = DateTime.Now;
                Console.WriteLine("dtStart:" + dtStart.ToString());
                Console.WriteLine("dtCurrent:" + dtCurrent.ToString());
                TimeSpan ts = dtCurrent.Subtract(dtStart);
                if (ts.Milliseconds < 35)
                {
                    IsScanningGunAuto = true;
                    Console.WriteLine("扫描枪;ts:" + ts.Milliseconds.ToString() + " Text:" + this.txtCustomerNo.Text.Trim());
                }
                else
                {
                    IsScanningGunAuto = false;
                    Console.WriteLine("手动输入;ts:" + ts.Milliseconds.ToString() + " Text:" + this.txtCustomerNo.Text.Trim());
                }
                dtStart = dtCurrent;
                Console.WriteLine("----------------------------------------");
            };
            this.txtCustomerNo.TbKeyDown += (sender, e) =>
            {
                if (this.txtCustomerNo.TbFocused)
                {

                    if (e.KeyCode == Keys.Enter)
                    {
                        if (IsScanningGunAuto)
                            ScanningGunAuto();
                        //else
                        //btnSeach_Click(null, null);
                        //this.txtCustomerName.Focus();
                    }

                }

            };

  

原文地址:https://www.cnblogs.com/51net/p/3863620.html