How can I read barcodes without having the user focus a text box first?

后端 未结 4 1152
栀梦
栀梦 2021-02-14 12:46

I recently acquired a Metrologic Barcode scanner (USB port), as everyone already knows it works as a keyboard emulator out of the box.

How do I configure the scanner and

4条回答
  •  醉梦人生
    2021-02-14 13:21

    You can use the OnShortcut event on a form to intercept keyboard presses. Check if the prefix you configured on the barcodescanner appears, and set as Handled al keypresses until you get the barcode scanner suffix. Within your Shortcut handler build up the barcode string

    The following code is adapted from something I use myself, but is untested in its current form.

        // Variables defined on Form object
    GettingBarcode : boolean;
    CurrentBarcode : string;
    TypedInShiftState: integer; // 16=shift, 17=ctrl, 18=alt
    
    procedure Form1.FormShortCut(var Msg: TWMKey; var Handled: Boolean);
    var
      Character:Char;
    begin
      Character:=Chr(MapVirtualKey(Msg.CharCode,MAPVK_VK_TO_CHAR));
      if GettingBarcode then
      begin
        // Take care of case 
        if (TypedInShiftState<>16) and CharInSet(Character,['A'..'Z']) then
            Character:=Chr(Ord(Character)+32);
        TypedInShiftState:=0;
        // Tab and Enter programmed as suffix on barcode scanner
        if CharInSet(Character,[#9, #13]) then
        begin
          // Do something with your barcode string
          try
            HandleBarcode(CurrentBarcode);
          finally
            CurrentBarcode:='';
            Handled:=true;
            GettingBarcode:=False;
          end;
        end
        else if CharInSet(Character,[#0..#31]) then
        begin
          TypedInShiftState:=Msg.CharCode;
          Handled:=True;
        end
        else begin
          CurrentBarcode:=CurrentBarcode+Character;
          Handled:=true;
        end;
      end
      else begin
        if Character=#0 then
        begin
          TypedInShiftState:=Msg.CharCode;
        end
        else if (TypedInShiftState=18) and (Character='A') then
        begin
          GettingBarcode:=True;
          CurrentBarcode:='';
          Handled:=true;
        end;
      end;
    end;
    

提交回复
热议问题