类文件:

C#类文件
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection; 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 = ;
string strBarCode = ""; private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if (nCode == )
{
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();
if (GetKeyNameText(barCode.ScanCode * , strKeyName, ) > )
{
barCode.KeyName = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
}
else
{
barCode.KeyName = "";
}
byte[] kbArray = new byte[];
uint uKey = ;
GetKeyboardState(kbArray); if (ToAscii(barCode.VirtKey, barCode.ScanCode, kbArray, ref uKey, ))
{
barCode.Ascll = uKey;
barCode.Chr = Convert.ToChar(uKey);
} TimeSpan ts = DateTime.Now.Subtract(barCode.Time); if (ts.TotalMilliseconds > )
{
strBarCode = barCode.Chr.ToString();
}
else
{
if ((msg.message & 0xff) == && strBarCode.Length > )
{
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 == )
{
//WH_KEYBOARD_LL=13
hKeyboardHook = SetWindowsHookEx(, new HookProc(KeyboardHookProc), Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[]), );
}
return (hKeyboardHook != );
} //卸载钩子
public bool Stop()
{
if (hKeyboardHook != )
{
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, "系统提示");
            }
        }
    }
}

C# Winform中无焦点状态下获取键盘输入或者USB扫描枪数据的更多相关文章

  1. 获取键盘输入或者USB扫描枪数据

    /// <summary> /// 获取键盘输入或者USB扫描枪数据 可以是没有焦点 应为使用的是全局钩子 /// USB扫描枪 是模拟键盘按下 /// 这里主要处理扫描枪的值,手动输入的 ...

  2. [C#.Net]全局钩子实现USB扫码枪无焦点状态下扫入

    https://www.cnblogs.com/masonlu/p/10105135.html

  3. QT无窗口状态下对键盘事件的监听

    Question:最近在搞linux下的一个客户端项目,需要接收键盘事件,但是又不能有界面,这种情况怎么处理呢? int main(int argc, char *argv[]) { QApplica ...

  4. WinForm 无焦点获取键盘输入

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  5. 无索引状态下比较DataTable的几种过滤方法效率

    先构造一个DataTable: public DataTable GetDataTable() { DataTable dtTmp = new DataTable(); dtTmp.Columns.A ...

  6. 在Delphi中使用键盘勾子获取键盘输入(译--5月7日)

    http://blog.sina.com.cn/s/blog_502b2e970100949s.html 获取键盘输入以控制无法接受输入焦点的控件考虑一些游戏,显示图片在TPainBox,但是TPai ...

  7. Java编程中获取键盘输入实现方法及注意事项

    Java编程中获取键盘输入实现方法及注意事项 1. 键盘输入一个数组 package com.wen201807.sort; import java.util.Scanner; public clas ...

  8. java利用Scanner获取键盘输入

    首发地址:我的网易博客 在运行一个java程序的时候,可能我们需要在运行的时候传递一些参数进去...咋办呢... java提供了一个Scanner类,利用这个类,我们可以很方便的获取键盘输入的参数.. ...

  9. System.in 获取键盘输入

    此处说明 两种使用System.in获取键盘输入的两种方法,分别是Scanner 和 InputStreamReader. 其中System.in 在System类中的定义如下: package co ...

随机推荐

  1. springMVC拦截器和过滤器总结

    拦截器: 用来对访问的url进行拦截处理 用处: 权限验证,乱码设置等 spring-mvc.xml文件中的配置: <beans xmlns="http://www.springfra ...

  2. 20169212《Linux内核原理与分析》 第十周作业

    云课堂回顾学习 1. 进程调度的时机 中断处理过程(包括时钟中断.I/O中断.系统调用和异常)中,直接调用schedule(),或者返回用户态时根据need_resched标记调用schedule() ...

  3. Gerald is into Art

    Gerald is into Art Gerald bought two very rare paintings at the Sotheby's auction and he now wants t ...

  4. clearfix清除浮动

    首先在很多很多年以前我们常用的清除浮动是这样的. 1 .clear{clear:both;line-height:0;} 现在可能还可以在很多老的站点上可以看到这样的代码,相当暴力有效的解决浮动的问题 ...

  5. mongodump 备份

    规划 副本集,其中加了个隐藏节点,用来做备份,所以备份脚本直接在隐藏节点做,目前数据不大,直接本机磁盘存储,后续如果数据集大,那么在本地存最近一天的备份,远程根据需求存储几天的备份 创建备份用户 db ...

  6. Electron-使用Electron开发第一个应用

    使用Electron开发第一个应用 Electron 应用的目录结构如下: app/ ├── package.json ├── main.js └── index.html 新建一个app文件夹 将这 ...

  7. MICAPS二次开发一些功能调用

    1.调用地图并将micaps文件加载地图上 IFileBindingService fbs = ServiceLocator.Current.GetInstance< IFileBindingS ...

  8. 解析txt文本,dom4j工具输出为xml文档

    有如下一个ttl.txt文本文档,每一行用空格隔开的三段分别代表主谓宾, 要将它们输出为xml格式文档 工具:dom4j,jar包导入MyEclipse的Java Project工程 代码如下: pa ...

  9. Cookie与Session用法

    以下是Cookie的完整实例 MyEclipse新建web Project工程,建两个jsp文件,如下 1.login.jsp <%@ page language="java" ...

  10. JQuery设置时间段下拉选择 时间下拉选择

    $(document).ready(function() { var arrT = []; var tt = "{0}:{1}"; for (var i = 0; i < 2 ...