C#操控 条形码扫描枪

转载收藏使用

===================================

// 条码扫描器

// 窗体部分相关代码:


using System;
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Text;  
using System.Windows.Forms;  
 
namespace ReadBadCode  
{  
   
public partial class frmTest : Form  
    {  
        BarCodeHook BarCode
= new BarCodeHook();  
       
public frmTest()  
        {  
            InitializeComponent();  
            BarCode.BarCodeEvent
+= new BarCodeHook.BarCodeDelegate(BarCode_BarCodeEvent);  
        }  
 
       
private delegate void ShowInfoDelegate(BarCodeHook.BarCodes barCode);  
       
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, FormClosedEventArgs e)  
        {  
            BarCode.Stop();  
        }  
 
       
private void textBox6_TextChanged(object sender, EventArgs e)  
        {  
           
if (textBox6.Text.Length > 0)  
            {  
                MessageBox.Show(textBox6.Text);  
            }  
        }  
    }  
}  

BarCodeHook  类相关代码:

using System;  
using System.Collections.Generic;  
using System.Text;  
using System.Runtime.InteropServices;  
using System.Reflection;  
 
namespace ReadBadCode  
{  
   
public class BarCodeHook  
    {  
       
public delegate void BarCodeDelegate(BarCodes barCode);  
       
public event BarCodeDelegate BarCodeEvent;  
 
       
public struct BarCodes  
        {  
           
public int VirtKey;      //虚拟码  
            public int ScanCode;     //扫描码  
            public string KeyName;   //键名  
            public uint AscII;       //AscII  
            public char Chr;         //字符  
 
           
public string BarCode;   //条码信息  
            public bool IsValid;     //条码是否有效  
            public DateTime Time;    //扫描时间  
        }  
 
       
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, HookProc lpfn, 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, StringBuilder lpBuffer, 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, IntPtr lParam);  
        BarCodes barCode
= new BarCodes();  
       
int hKeyboardHook = 0;  
       
string strBarCode = "";  
 
       
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)  
        {  
           
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, new HookProc(KeyboardHookProc), Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);  
            }  
           
return (hKeyboardHook != 0);  
        }  
 
       
// 卸载钩子   
        public bool Stop()  
        {  
           
if (hKeyboardHook != 0)  
            {  
               
return UnhookWindowsHookEx(hKeyboardHook);  
            }  
           
return true;  
        }  
    }  

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于使用得力扫描枪扫描二维码,你可以使用以下步骤在C#中实现: 1. 确保你的得力扫描枪已经连接到计算机,并且被识别为HID(Human Interface Device)设备。 2. 使用Windows API来读取扫描枪的输入数据。你可以通过使用`RegisterRawInputDevices`函数来注册输入设备,并使用`WM_INPUT`消息来接收输入数据。 下面是一个基本的示例代码,演示了如何使用C#来处理得力扫描枪的输入数据: ```csharp using System; using System.Runtime.InteropServices; using System.Windows.Forms; class Program { private const int WM_INPUT = 0x00FF; private const int RID_INPUT = 0x10000003; private const int RIDEV_INPUTSINK = 0x00000100; private const int RIDEV_DEVNOTIFY = 0x00002000; [StructLayout(LayoutKind.Sequential)] struct RAWINPUTDEVICELIST { public IntPtr hDevice; public int dwType; } [DllImport("user32.dll")] static extern uint GetRawInputDeviceList(IntPtr pRawInputDeviceList, ref uint uiNumDevices, uint cbSize); [DllImport("user32.dll")] static extern bool RegisterRawInputDevices(RAWINPUTDEVICELIST[] pRawInputDeviceList, uint uiNumDevices, uint cbSize); [DllImport("user32.dll")] static extern uint GetRawInputData(IntPtr hRawInput, uint uiCommand, IntPtr pData, ref uint pcbSize, uint cbSizeHeader); static void Main() { // 注册输入设备 RAWINPUTDEVICELIST[] rawInputDeviceList = new RAWINPUTDEVICELIST[1]; rawInputDeviceList[0].dwType = RID_INPUT; rawInputDeviceList[0].hDevice = IntPtr.Zero; if (!RegisterRawInputDevices(rawInputDeviceList, 1, (uint)Marshal.SizeOf<RAWINPUTDEVICELIST>())) { Console.WriteLine("无法注册输入设备。"); return; } // 创建窗口来接收输入消息 NativeWindow window = new NativeWindow(); window.CreateHandle(new CreateParams()); // 循环接收输入消息 while (true) { Application.DoEvents(); } } protected override void WndProc(ref Message m) { if (m.Msg == WM_INPUT) { // 读取输入数据 uint size = 0; GetRawInputData(m.LParam, RID_INPUT, IntPtr.Zero, ref size, (uint)Marshal.SizeOf<RAWINPUTHEADER>()); IntPtr buffer = Marshal.AllocHGlobal((int)size); try { GetRawInputData(m.LParam, RID_INPUT, buffer, ref size, (uint)Marshal.SizeOf<RAWINPUTHEADER>()); // 在这里处理扫描枪的输入数据 // 解析二维码数据并进行相关操作 // 例如,你可以通过ZXing库来解码二维码 // 你可以在这里将二维码数据传递给其他方法进行处理 ProcessQRCodeData(buffer); } finally { Marshal.FreeHGlobal(buffer); } } base.WndProc(ref m); } private void ProcessQRCodeData(IntPtr buffer) { // 在这里处理扫描枪输入的二维码数据 // 解析二维码并进行相关操作 // 例如,你可以使用ZXing库来解码二维码 // 以下是一个使用ZXing库解码二维码的示例 // 你需要安装ZXing.Net库,通过NuGet包管理器安装 ZXing.BarcodeReader barcodeReader = new ZXing.BarcodeReader(); ZXing.Result result = barcodeReader.Decode(new Bitmap(/* 这里是图像数据来源 */)); if (result != null) { string decodedText = result.Text; Console.WriteLine("解码结果: " + decodedText); } else { Console.WriteLine("未能解码二维码。"); } } } ``` 请注意,上述代码只是一个基本示例,你需要根据实际情况进行适当的修改和调整。在代码中,我们使用`WM_INPUT`消息来接收扫描枪的输入数据,并通过`RegisterRawInputDevices`函数注册输入设备。然后,我们创建了一个窗口来接收输入消息,并在`WndProc`方法中处理输入数据。你可以在`ProcessQRCodeData`方法中解析扫描枪输入的二维码数据。 希望这可以帮助到你!如果你有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值