C# Winform中无焦点状态下获取键盘输入或者USB扫描枪数据

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


namespace Common
{
   public class BardCodeHooK
   {
       public delegate void BardCodeDeletegate(BarCodes barCode);
       public event BardCodeDeletegate BarCodeEvent;


       public struct BarCodes
       {
           public int VirtKey;//虚拟吗
           public int ScanCode;//扫描码
           public string KeyName;//键名
           public uint Ascll;//Ascll
           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 IParam, 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[] lpKeySate, 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(225);
                   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.Ascll = uKey;
                       barCode.Chr = Convert.ToChar(uKey);
                   }


                   TimeSpan ts = DateTime.Now.Subtract(barCode.Time);


                   if (ts.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;
        }
    }
}



页面中用法:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Common
{
    public partial class FrmMain : Form
    {
        BardCodeHooK BarCode = new BardCodeHooK();
        public FrmMain()
        {
            InitializeComponent();
            BarCode.BarCodeEvent += new BardCodeHooK.BardCodeDeletegate(BarCode_BarCodeEvent);
        }
        private delegate void ShowInfoDelegate(BardCodeHooK.BarCodes barCode);
        private void ShowInfo(BardCodeHooK.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.Ascll.ToString();
                textBox5.Text = barCode.Chr.ToString();
                textBox6.Text = barCode.IsValid? barCode.BarCode : "";//是否为扫描枪输入,如果为true则是 否则为键盘输入
                textBox7.Text += barCode.KeyName;
                //MessageBox.Show(barCode.IsValid.ToString());
            }
        }
        //C#中判断扫描枪输入与键盘输入
        //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 ;
        //}
 
        void BarCode_BarCodeEvent(BardCodeHooK.BarCodes barCode)
        {
            ShowInfo(barCode);
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            BarCode.Start();
        }
        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            BarCode.Stop();
        }
        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            if (textBox6.Text.Length > 0)
            {
                MessageBox.Show("条码长度:" + textBox6.Text.Length + "\n条码内容:" + textBox6.Text, "系统提示");
            }
        }
    }
}

  • 2
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
基恩士扫描winform是一种常用的扫描设备,用于扫描物品上的条形码或二维码。在winform开发环境,我们可以通过使用基恩士扫描的SDK来实现与扫描的连接和数据读取。 首先,我们需要在winform应用程序引入基恩士扫描SDK,并在项目设置添加相应的引用。接下来,我们可以创建一个扫描的实例,并通过调用其相应的方法来与扫描进行交互。 针对通过TCP/IP读取网口数据的需求,我们可以使用Socket类来实现。我们首先需要创建一个Socket对象,并通过其Connect方法来连接扫描的IP地址和端口号。一旦连接成功,我们可以使用NetworkStream对象来读取扫描传输的数据。 在获取扫描传来的数据后,我们可以将其显示在winform应用程序的界面上。可以通过创建一个文本框或标签来显示扫描到的条形码或二维码。 需要注意的是,由于扫描数据是通过事件的方式传递的,我们需要在代码订阅扫描的事件,并在事件处理方法获取扫描到的数据。同时,在应用程序退出时,我们需要及时断开与扫描的连接,释放相关资源。 总之,基恩士扫描winform根据TCP/IP读取网口数据的实现过程包括引入SDK、创建扫描实例、连接扫描、使用Socket类读取数据,并在界面上显示扫描到的数据。通过以上步骤,我们可以实现扫描winform应用程序的数据交互。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值