说明:
- 继上次串口的源码分享后,这个周末根据串口底层封装的思想,这个周末,把好多人"望而却步"的USB设备数据读取做了一个底层封装。
- 这次也是通过绑定事件的形式获取USB读取的数据,然后广播形式广播获取的USB数据,我这里部分源码虽然是网上的,但是网上的有不少BUG。
- 连续扫个十几次就over了,我做了一个bug的修复,并且已经封装至底层,用到了全局钩子,不管窗体有无焦点,都可以获取数据。
- 实测我连续扫描100次没有出现over现象,具体自己测吧,代码长度太长,分段显示,USB数据操作在下一段。
源码:
[C#] 纯文本查看 复制代码 /// <summary>
/// USB数据获取/传输事件
/// 当前版本: 1.0
/// 作者: 孙建伟
/// 创建日期: 2015-08-21
/// 最后修改日期: 2015-08-22
/// </summary>
public class USBDataArgs : EventArgs
{
/// <summary>
/// 码信息
/// </summary>
public BarCodes USBBarCodes
{
get;
set;
}
/// <summary>
/// 构造方法
/// </summary>
/// <param name="usbbarcode"></param>
public USBDataArgs(BarCodes usbbarcode)
{
USBBarCodes = usbbarcode;
}
}
#region 码信息构造
/// <summary>
/// 码信息
/// </summary>
public struct BarCodes
{
/// <summary>
/// 虚拟码
/// </summary>
public int VirtKey;//虚拟码
/// <summary>
/// 扫描码
/// </summary>
public int ScanCode;//扫描码
/// <summary>
/// 键名
/// </summary>
public string KeyName;//键名
/// <summary>
/// Ascii
/// </summary>
public uint Ascii;//Ascii
/// <summary>
/// 字符
/// </summary>
public char Chr;//字符
/// <summary>
/// 原始 字符
/// </summary>
public string OriginalChrs; //原始 字符
/// <summary>
/// 原始 ASCII
/// </summary>
public string OriginalAsciis;//原始 ASCII
/// <summary>
/// 原始数据条码
/// </summary>
public string OriginalBarCode; //原始数据条码
/// <summary>
/// 条码是否有效
/// </summary>
public bool IsValid;//条码是否有效
/// <summary>
/// 扫描时间
/// </summary>
public DateTime Time;//扫描时间,
/// <summary>
/// 条码信息 保存最终的条码
/// </summary>
public string BarCode;//条码信息 保存最终的条码
/// <summary>
/// 构造
/// </summary>
/// <param name="virkey">虚拟码</param>
/// <param name="scancode">扫描码</param>
/// <param name="keyname">键名</param>
/// <param name="ascii">Ascii码</param>
/// <param name="chr">字符</param>
/// <param name="originalchrs">原始 字符</param>
/// <param name="originalasciis">原始 ASCII</param>
/// <param name="originalbarcode">原始数据条码</param>
/// <param name="isvalid">条码是否有效</param>
/// <param name="time">扫描时间</param>
/// <param name="barcode">条码信息 保存最终的条码</param>
public BarCodes(int virkey, int scancode, string keyname, uint ascii, char chr, string originalchrs, string originalasciis, string originalbarcode, bool isvalid, DateTime time, string barcode)
{
VirtKey = virkey;
ScanCode = scancode;
KeyName = keyname;
Ascii = ascii;
Chr = chr;
OriginalChrs = originalchrs;
OriginalAsciis = originalasciis;
OriginalBarCode = originalbarcode;
IsValid = isvalid;
Time = time;
BarCode = barcode;
}
}
#endregion
[C#] 纯文本查看 复制代码 /// <summary>
///获取USB设备扫描值,目前测试通过的有USB读卡器、USB扫描枪,有点缺陷就是USB设备读取的值都会处理,具体USB格式需要在程序中处理,绑定事件到BarCodeEvent
/// </summary>
public static class USBBarCodeBroadcast
{
#region DLLImport
/// <summary>
/// 安装钩子的函数
/// </summary>
/// <param name="idHook"></param>
/// <param name="lpfn"></param>
/// <param name="hInstance"></param>
/// <param name="threadId"></param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
/// <summary>
/// 卸下钩子的函数
/// </summary>
/// <param name="idHook"></param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(int idHook);
/// <summary>
/// 下一个钩挂的函数
/// </summary>
/// <param name="idHook"></param>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[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);
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string name);
#endregion
/// <summary>
/// 钩子
/// </summary>
private static HookProc hookproc;
/// <summary>
/// 事件消息
/// </summary>
private struct EventMsg
{
/// <summary>
/// 消息
/// </summary>
public int message;
/// <summary>
/// 消息参数
/// </summary>
public int paramL;
/// <summary>
/// 消息参数
/// </summary>
public int paramH;
/// <summary>
/// 事件
/// </summary>
public int Time;
/// <summary>
/// 窗口句柄
/// </summary>
public int hwnd;
}
///// <summary>
///// 获取USB传输数据委托
///// </summary>
///// <param name="e">自定义事件</param>
//public delegate void DelegateBarCode(USBDataArgs e);
/// <summary>
/// 全局钩子委托
/// </summary>
/// <param name="nCode"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
static BarCodes barCode = new BarCodes();
/// <summary>
/// 事件参数
/// </summary>
static internal USBDataArgs usbargs = new USBDataArgs(barCode);
/// <summary>
/// 获取USB传输数据委托广播事件
/// </summary>
public static event Action<USBDataArgs> BarCodeEvent;
/// <summary>
/// hKeyboardHook
/// </summary>
static int hKeyboardHook = 0;
/// <summary>
/// 获取的码
/// </summary>
static StringBuilder sbBarCode = new StringBuilder();
private static int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
int i_calledNext = -10;
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.Ascii = uKey;
barCode.Chr = Convert.ToChar(uKey);
barCode.OriginalChrs += " " + Convert.ToString(barCode.Chr);
barCode.OriginalAsciis += " " + Convert.ToString(barCode.Ascii);
barCode.OriginalBarCode += Convert.ToString(barCode.Chr);
}
TimeSpan ts = DateTime.Now.Subtract(barCode.Time);
if (ts.TotalMilliseconds > 50)
{//时间戳,大于50 毫秒表示手动输入
// strBarCode = barCode.Chr.ToString();
sbBarCode.Remove(0, sbBarCode.Length);
sbBarCode.Append(barCode.Chr.ToString());
barCode.OriginalChrs = " " + Convert.ToString(barCode.Chr);
barCode.OriginalAsciis = " " + Convert.ToString(barCode.Ascii);
barCode.OriginalBarCode = Convert.ToString(barCode.Chr);
}
else
{
if ((msg.message & 0xff) == 13 && sbBarCode.Length > 3)
{//回车
// barCode.BarCode = strBarCode;
// barCode.BarCode = sbBarCode.ToString();
barCode.BarCode = barCode.OriginalBarCode;
barCode.IsValid = true;
sbBarCode.Remove(0, sbBarCode.Length);
}
sbBarCode.Append(barCode.Chr.ToString());
}
try
{
if (BarCodeEvent != null && barCode.IsValid)
{
usbargs.USBBarCodes = barCode;
BarCodeEvent(usbargs);
barCode.BarCode = "";
barCode.OriginalChrs = "";
barCode.OriginalAsciis = "";
barCode.OriginalBarCode = "";
}
}
catch(Exception ex)
{
//JLog.Record("钩子错误",ex);//记录日志
}
finally
{
barCode.IsValid = false; //最后一定要 设置barCode无效
barCode.Time = DateTime.Now;
//i_calledNext = CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);//事件往下传
}
}
}
if (i_calledNext == -10)
{
i_calledNext = CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
return i_calledNext;
}
//安装钩子
/// <summary>
/// 安装全局钩子
/// </summary>
/// <returns></returns>
public static bool Start()
{
//BarCodeEvent = null;//初始化时移除事件订阅
if (hKeyboardHook == 0)
{
hookproc = new HookProc(KeyboardHookProc);
//GetModuleHandle 函数 替代 Marshal.GetHINSTANCE
//防止在 framework4.0中 注册钩子不成功
IntPtr modulePtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
//WH_KEYBOARD_LL=13
//全局钩子 WH_KEYBOARD_LL
// hKeyboardHook = SetWindowsHookEx(13, hookproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
hKeyboardHook = SetWindowsHookEx(13, hookproc, modulePtr, 0);
}
return (hKeyboardHook != 0);
}
//卸载全局钩子
/// <summary>
/// 卸载全局钩子
/// </summary>
/// <returns></returns>
public static bool Stop()
{
BarCodeEvent = null;//取消所有事件
if (hKeyboardHook != 0)
{
bool bOK = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = 0;
return bOK;
}
return true;
}
}
|
评分
-
查看全部评分
|