本文轉載: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();
}
}
};
