条码扫描器接口编程

news/2025/1/1 13:26:27/

目前的条形码扫描器有点类似外接键盘(其实从消息传送上它就相当于一个键盘),把输入焦点定位到可输入的控件上,一扫描相应的条形码信息就输入到文本框中去了,但是如果没有输入焦点,或另一个不相干的程序获得输入焦点,那就有点乱套了。我想实现的是,不管什么情况,只要扫描器一工作,我的程序就能自动激活,并能获得当前输入的条形码信息。实现思路:我用的USB口的条形码扫描器,仔细分析了一下,扫描成功后,以键盘按键消息的形式把条形码输入信息通知给系统。这样通过键盘钩子就可以方便的获得该信息了。但是,怎样区分信息是键盘还是条形码输入的哪?很简单,条形码扫描器在很短的时间内输入了至少3个字符以上信息,并且以“回车”作为结束字符,在这种思想指引下,很完美的实现了预定功能。  

 

窗体相关代码:

view plaincopy to clipboardprint?
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
using System;  
usingSystem.Collections.Generic;  
usingSystem.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Text;  
usingSystem.Windows.Forms;  
 
namespace ReadBadCode  
 
    publicpartial class frmTest :Form  
    
       BarCodeHook BarCode = newBarCodeHook();  
       public frmTest()  
        
           InitializeComponent();  
           BarCode.BarCodeEvent += newBarCodeHook.BarCodeDelegate(BarCode_BarCodeEvent);  
        
 
       private delegate void ShowInfoDelegate(BarCodeHook.BarCodesbarCode);  
       private void ShowInfo(BarCodeHook.BarCodesbarCode)  
        
           if (this.InvokeRequired)  
            
               this.BeginInvoke(new ShowInfoDelegate(ShowInfo), new object[] {barCode });  
            
           else 
            
               textBox1.Text =barCode.KeyName;  
               textBox2.Text =barCode.VirtKey.ToString();  
               textBox3.Text =barCode.ScanCode.ToString();  
               textBox4.Text =barCode.AscII.ToString();  
               textBox5.Text =barCode.Chr.ToString();  
               textBox6.Text = barCode.IsValid ? barCode.BarCode :"";  
            
        
 
       void BarCode_BarCodeEvent(BarCodeHook.BarCodesbarCode)  
        
           ShowInfo(barCode);  
        
 
       private void frmTest_Load(object sender, EventArgse)  
        
           BarCode.Start();  
        
 
       private void frmTest_FormClosed(object sender, FormClosedEventArgse)  
        
           BarCode.Stop();  
        
 
       private void textBox6_TextChanged(object sender, EventArgse)  
        
           if (textBox6.Text.Length >0)  
            
               MessageBox.Show(textBox6.Text);  
            
        
    
 
 
  
 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ReadBadCode
{
    publicpartial class frmTest : Form
    {
       BarCodeHook BarCode = new BarCodeHook();
       public frmTest()
       {
           InitializeComponent();
           BarCode.BarCodeEvent += newBarCodeHook.BarCodeDelegate(BarCode_BarCodeEvent);
       }

       private delegate void ShowInfoDelegate(BarCodeHook.BarCodesbarCode);
       private void ShowInfo(BarCodeHook.BarCodes barCode)
       {
           if (this.InvokeRequired)
           {
               this.BeginInvoke(new ShowInfoDelegate(ShowInfo), new object[] {barCode });
           }
           else
           {
               textBox1.Text = barCode.KeyName;
               textBox2.Text = barCode.VirtKey.ToString();
               textBox3.Text = barCode.ScanCode.ToString();
               textBox4.Text = barCode.AscII.ToString();
               textBox5.Text = barCode.Chr.ToString();
               textBox6.Text = barCode.IsValid ? barCode.BarCode : "";
           }
       }

       void BarCode_BarCodeEvent(BarCodeHook.BarCodes barCode)
       {
           ShowInfo(barCode);
       }

       private void frmTest_Load(object sender, EventArgs e)
       {
           BarCode.Start();
       }

       private void frmTest_FormClosed(object sender, FormClosedEventArgse)
       {
           BarCode.Stop();
       }

       private void textBox6_TextChanged(object sender, EventArgs e)
       {
           if (textBox6.Text.Length > 0)
           {
               MessageBox.Show(textBox6.Text);
           }
       }
    }
}

 
 

BarCodeHook 类:

view plaincopy to clipboardprint?
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
using System;  
usingSystem.Collections.Generic;  
using System.Text;  
usingSystem.Runtime.InteropServices;  
using System.Reflection;  
 
namespace ReadBadCode  
 
    public classBarCodeHook  
    
       public delegate void BarCodeDelegate(BarCodesbarCode);  
       public event BarCodeDelegateBarCodeEvent;  
 
       public struct BarCodes  
        
           public intVirtKey;     //虚拟码  
           public intScanCode;    //扫描码  
           public string KeyName;  //键名  
           public uintAscII;      //AscII  
           public charChr;        //字符  
 
           public string BarCode;  //条码信息  
           public boolIsValid;    //条码是否有效  
           public DateTimeTime;   //扫描时间  
        
 
       private struct EventMsg  
        
           public int message;  
           public int paramL;  
           public int paramH;  
           public int Time;  
           public int hwnd;  
        
         
       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention=CallingConvention.StdCall)]  
       private static extern int SetWindowsHookEx(int idHook, HookProclpfn, IntPtr hInstance, intthreadId);  
 
       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention=CallingConvention.StdCall)]  
       private static extern bool UnhookWindowsHookEx(intidHook);  
 
       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention=CallingConvention.StdCall)]  
       private static extern int CallNextHookEx(int idHook, int nCode,Int32 wParam, IntPtrlParam);  
 
       [DllImport("user32", EntryPoint ="GetKeyNameText")]  
       private static extern int GetKeyNameText(int lParam, StringBuilderlpBuffer, int nSize);  
 
       [DllImport("user32", EntryPoint ="GetKeyboardState")]  
       private static extern int GetKeyboardState(byte[]pbKeyState);  
 
       [DllImport("user32", EntryPoint ="ToAscii")]  
       private static extern bool ToAscii(int VirtualKey, int ScanCode,byte[] lpKeyState, ref uint lpChar, intuFlags);  
 
       delegate int HookProc(int nCode, Int32 wParam, IntPtrlParam);  
       BarCodes barCode = newBarCodes();  
       int hKeyboardHook = 0;  
       string strBarCode = "";  
 
       private int KeyboardHookProc(int nCode, Int32 wParam, IntPtrlParam)  
        
           if (nCode == 0)  
            
               EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam,typeof(EventMsg));  
 
               if (wParam == 0x100)  //WM_KEYDOWN = 0x100  
                
                   barCode.VirtKey = msg.message &0xff; //虚拟码  
                   barCode.ScanCode = msg.paramL &0xff; //扫描码  
 
                   StringBuilder strKeyName = newStringBuilder(255);  
                   if (GetKeyNameText(barCode.ScanCode * 65536, strKeyName, 255)> 0)  
                    
                       barCode.KeyName = strKeyName.ToString().Trim(new char[] { ' ', '\0'});  
                    
                   else 
                    
                       barCode.KeyName = "";  
                    
 
                   byte[] kbArray = newbyte[256];  
                   uint uKey = 0;  
                   GetKeyboardState(kbArray);                                          
                   if (ToAscii(barCode.VirtKey, barCode.ScanCode, kbArray, ref uKey,0))  
                    
                       barCode.AscII = uKey;  
                       barCode.Chr =Convert.ToChar(uKey);  
                    
 
                   if (DateTime.Now.Subtract(barCode.Time).TotalMilliseconds>50)   
                    
                       strBarCode =barCode.Chr.ToString();  
                    
                   else 
                    
                       if ((msg.message & 0xff) == 13&& strBarCode.Length> 3)  //回车  
                        
                           barCode.BarCode =strBarCode;  
                           barCode.IsValid = true;  
                        
                       strBarCode +=barCode.Chr.ToString();  
                    
 
                   barCode.Time =DateTime.Now;  
                   if (BarCodeEvent != null)BarCodeEvent(barCode);   //触发事件  
                   barCode.IsValid = false;  
                
            
           return CallNextHookEx(hKeyboardHook, nCode, wParam,lParam);            
        
          
       // 安装钩子   
       public bool Start()  
        
           if (hKeyboardHook == 0)  
            
               //WH_KEYBOARD_LL = 13  
               hKeyboardHook = SetWindowsHookEx(13, newHookProc(KeyboardHookProc),Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);  
            
           return (hKeyboardHook !=0);  
        
 
       // 卸载钩子   
       public bool Stop()  
        
           if (hKeyboardHook != 0)  
            
               returnUnhookWindowsHookEx(hKeyboardHook);  
            
           return true;  
        
    

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;

namespace ReadBadCode
{
    public classBarCodeHook
    {
       public delegate void BarCodeDelegate(BarCodes barCode);
       public event BarCodeDelegate BarCodeEvent;

       public struct BarCodes
       {
           public intVirtKey;     //虚拟码
           public intScanCode;    //扫描码
           public string KeyName;  //键名
           public uintAscII;      //AscII
           public charChr;        //字符

           public string BarCode;  //条码信息
           public boolIsValid;    //条码是否有效
           public DateTimeTime;   //扫描时间
       }

       private struct EventMsg
       {
           public int message;
           public int paramL;
           public int paramH;
           public int Time;
           public int hwnd;
       }
      
       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention= CallingConvention.StdCall)]
       private static extern int SetWindowsHookEx(int idHook, HookProclpfn, IntPtr hInstance, int threadId);

       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention= CallingConvention.StdCall)]
       private static extern bool UnhookWindowsHookEx(int idHook);

       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention= CallingConvention.StdCall)]
       private static extern int CallNextHookEx(int idHook, int nCode,Int32 wParam, IntPtr lParam);

       [DllImport("user32", EntryPoint = "GetKeyNameText")]
       private static extern int GetKeyNameText(int lParam, StringBuilderlpBuffer, int nSize);

       [DllImport("user32", EntryPoint = "GetKeyboardState")]
       private static extern int GetKeyboardState(byte[] pbKeyState);

       [DllImport("user32", EntryPoint = "ToAscii")]
       private static extern bool ToAscii(int VirtualKey, int ScanCode,byte[] lpKeyState, ref uint lpChar, int uFlags);

       delegate int HookProc(int nCode, Int32 wParam, IntPtrlParam);
       BarCodes barCode = new BarCodes();
       int hKeyboardHook = 0;
       string strBarCode = "";

       private int KeyboardHookProc(int nCode, Int32 wParam, IntPtrlParam)
       {
           if (nCode == 0)
           {
               EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam,typeof(EventMsg));

               if (wParam == 0x100)  //WM_KEYDOWN = 0x100
               {
                   barCode.VirtKey = msg.message &0xff;  //虚拟码
                   barCode.ScanCode = msg.paramL &0xff;  //扫描码

                   StringBuilder strKeyName = new StringBuilder(255);
                   if (GetKeyNameText(barCode.ScanCode * 65536, strKeyName, 255)> 0)
                   {
                       barCode.KeyName = strKeyName.ToString().Trim(new char[] { ' ', '\0'});
                   }
                   else
                   {
                       barCode.KeyName = "";
                   }

                   byte[] kbArray = new byte[256];
                   uint uKey = 0;
                   GetKeyboardState(kbArray);                                       
                   if (ToAscii(barCode.VirtKey, barCode.ScanCode, kbArray, ref uKey,0))
                   {
                       barCode.AscII = uKey;
                       barCode.Chr = Convert.ToChar(uKey);
                   }

                   if (DateTime.Now.Subtract(barCode.Time).TotalMilliseconds> 50)
                   {
                       strBarCode = barCode.Chr.ToString();
                   }
                   else
                   {
                       if ((msg.message & 0xff) == 13&& strBarCode.Length> 3)   //回车
                       {
                           barCode.BarCode = strBarCode;
                           barCode.IsValid = true;
                       }
                       strBarCode += barCode.Chr.ToString();
                   }

                   barCode.Time = DateTime.Now;
                   if (BarCodeEvent != null)BarCodeEvent(barCode);   //触发事件
                   barCode.IsValid = false;
               }
           }
           return CallNextHookEx(hKeyboardHook, nCode, wParam,lParam);         
       }
       
       // 安装钩子
       public bool Start()
       {
           if (hKeyboardHook == 0)
           {
               //WH_KEYBOARD_LL = 13
               hKeyboardHook = SetWindowsHookEx(13, newHookProc(KeyboardHookProc),Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);
           }
           return (hKeyboardHook != 0);
       }

       // 卸载钩子
       public bool Stop()
       {
           if (hKeyboardHook != 0)
           {
               return UnhookWindowsHookEx(hKeyboardHook);
           }
           return true;
       }
    }
}
 



http://www.ppmy.cn/news/172315.html

相关文章

python读取usb扫码枪数据_仅在数据可用时从USB条形码扫描仪读取

更新时间: 我已经成功地用Python读取了一个USB条码扫描器。如果是空的,我希望能够转义fp.read(),并检查用户是否按下了左LCD按钮def read Barcode lcd.backlight(lcd.GREEN) hid = { 4: a, 5: b, 6: c, 7: d, 8: e, 9: f, 10: g, 11: h, 12: i, 13: j, 14: k, 15: l, 16: m,…

条形码扫描器会受到光波和无线电波的影响吗?

条形码扫描器会受到光波和无线电波的影响吗? 条形码是由一系列不同宽度的平行黑条和空格组成。每个条和空格的组合或序列都是一个代码,表示诸如产品类型、大小、制造商或运输来源等信息。条形码结构如图1所示。 条形码通常有不同的大小。条形码的大小…

树莓派linux扫码枪,树莓派应用:摄像头条形码扫描

树莓派小而强大,有非常多的应用场景。这里分享下使用树莓派,摄像头,以及C和Python代码来实现一个条形码扫描工具。之前分享过如何把OpenCV Python获取的图像传递到C层处理,会用到里面的代码。 测试环境 设备: Raspberry Pi 3 系统: RASPBIAN JESSIE WITH PIXEL 准备工作 Dy…

java中扫描仪关闭语句_在本机条形码扫描仪中添加关闭按钮

自定义phonegap-plugin-barcodescanner 在项目根目录中... 1 - 创建目录和克隆插件 $ mkdir customPlugins $ cd customPlugins $ cd .. 2 - 删除旧版插件 检查phonegap-plugin-barcodescanner是否在插件中,还删除config.xml或package.json中可能的旧引用 . $ ionic…

亚马逊条码打印_使用亚马逊的条形码扫描仪轻松从手机上购买任何东西

亚马逊条码打印 Sometimes you just want things to be simple, and whether you want to buy a book, DVD, or even products like shaving cream and dry goods, you can do it in a snap with Amazon’s mobile app. If you’re a Prime member, it’s free 2-day shipping …

工业条码扫描仪全国产化电子元件推荐方案

方案概述: 条码扫描仪由光传感器, 高清摄像头, USB电源控制器, 键盘和触摸屏控制器等构成, 进行 信息采集并传输给MCU微控制器进行处理 , 且显示在屏幕上 , 配备有一个USB2. 0端口。条码 扫描仪…

js怎么获取扫码枪条码_如何使用JavaScript获取扫码枪扫描得到的条形码

如何使用JavaScript获取扫码枪扫描得到的条形码 发布时间:2020-07-17 13:37:44 来源:亿速云 阅读:94 作者:小猪 这篇文章主要讲解了如何使用JavaScript获取扫码枪扫描得到的条形码,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。 下面通过实…

C++编程过程中常见的崩溃原因

程序运行中常见崩溃原因总结 常见的崩溃原因如何避免共勉 常见的崩溃原因 工作中经常会碰见程序运行时崩溃的问题,这里就个人经常碰到的崩溃原因做一归纳。其常见崩溃的原因如下: 【1】空指针调用函数导致。 表现在指针为被赋有效值,依旧为空…