2013-07-04 144 views
1

如何在我的C#應用​​程序中讀取背景中的條碼文本?我google搜索,但它沒用。和其他資源在stackoverflow不接近我所需要的。我想在後臺讀取條形碼。我想知道數據是來自條形碼還是鍵盤。如果數據來自條形碼,則即使文本框突出顯示,它也不能顯示在文本框上。我得到了類似的代碼,計算器,但如果有窗口文本的存在,則文本框將包含條碼數據;我不想要。 鏈接:get barcode reader value form background monitoringC#+ USB條碼閱讀器

DateTime _lastKeystroke = new DateTime(0); 
    List<char> _barcode = new List<char>(10); 

    private void Form1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     // check timing (keystrokes within 100 ms) 
     TimeSpan elapsed = (DateTime.Now - _lastKeystroke); 
     if (elapsed.TotalMilliseconds > 100) 
      _barcode.Clear(); 

     // record keystroke & timestamp 
     _barcode.Add(e.KeyChar); 
     _lastKeystroke = DateTime.Now; 

     // process barcode 
     if (e.KeyChar == 13 && _barcode.Count > 0) { 
      string msg = new String(_barcode.ToArray()); 
      MessageBox.Show(msg); 
      _barcode.Clear(); 
     } 
    } 

回答

2

大多數條碼掃描器簡單地充當鍵盤輸入和快速/簡單的解決辦法是把一個文本框「眼不見」。一個例子是這樣的:

// Pseudo code (could be Web, Windows etc) 
public void Form1_Load() 
{ 
    txtBarcodeScanner.Top = -10000; 
    txtBarcodeScanner.Left = -10000; 
    txtBarcodeScanner.Width = 10; 
    txtBarcodeScanner.Height = 10; 
    txtBarcodeScanner.Focus(); 
} 

這樣的輸入可以通過txtBarcodeScanner被捕獲,但將不可見和條形碼不會見過被抓獲,但會觸發KeyDown

+0

而如果我在我的應用程序的多個文本框後按下。我需要在同一窗口中記錄條形碼數據以及文本框數據。你可能會認爲我的申請像POS一樣。 – Redone

+0

在這種情況下,你通常有一個計時器,如果說在x秒內沒有用戶活動(即打字)然後強制焦點回到條形碼文本框或有一個按鈕,操作員點擊叫** **掃描彈出窗體說「請立即掃描...」,其中包含隱藏的文本框。這取決於你當然的用戶體驗。 – Belogix

+1

@Belogix爲什麼不只是爲WinForm Textbox設置[Control.Visible](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.visible.aspx)而不是移動它?這樣你就可以擁有一個綁定到文本框可見性的屬性。 –

0

條碼設備,如:鍵盤。

1當輸入條碼,按F12

2進入插入條形碼

private void textbox_Keydown(object sender, KeyEventArgs e) 
{ 
    if(e.KeyCode == Keys.F12){ 
    Textbox.Focus(); 
    } 
    if(e.KeyCode == Keys.Enter){ 
    /// after enter barcode 
    /// save 
    } 

} 
+0

'Textbox.Focus();'??? – LarsTech

+0

我認爲在同一事件處理程序中處理F12和Enter鍵是有意義的--F12行爲適用於除條形碼輸入框之外的所有可聚焦控件,輸入行爲僅適用於條形碼輸入框。 –

+0

已成功通過測試 - 輸入條形碼前 - 按下f12 - 輸入條形碼 - 按下輸入 – emad