无焦点获取条码枪返回值示例
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.runtime.interopservices;
using system.reflection;
namespace booklibrarymanagement.commontools
{
class barcodehook
{
public delegate void barcodedelegate(barcodes barcode);
public event barcodedelegate barcodeevent;
public struct barcodes
{
public int virtkey; //虚拟码
public int scancode; //扫描码
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);
delegate int hookproc(int ncode, int32 wparam, intptr lparam);
barcodes barcode = new barcodes();
int hkeyboardhook = 0;
list<char> _barcode = new list<char>(100);
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; //扫描码
if (datetime.now.subtract(barcode.time).totalmilliseconds > 100)
{
_barcode.clear();
}
else
{
if ((msg.message & 0xff) == 13 && _barcode.count > 0) //回车
{
barcode.barcode = new string(_barcode.toarray());
barcode.isvalid = true;
_barcode.clear();
}
}
barcode.time = datetime.now;
if (barcodeevent != null) barcodeevent(barcode); //触发事件
barcode.isvalid = false;
_barcode.add(convert.tochar(msg.message & 0xff));
}
}
return callnexthookex(hkeyboardhook, ncode, wparam, lparam);
}
private static hookproc hookproc;
// 安装钩子
public bool start()
{
if (hkeyboardhook == 0)
{
hookproc = new hookproc(keyboardhookproc);
//wh_keyboard_ll = 13
hkeyboardhook = setwindowshookex(13, hookproc, marshal.gethinstance(assembly.getexecutingassembly().getmodules()[0]), 0);
}
return (hkeyboardhook != 0);
}
// 卸载钩子
public bool stop()
{
if (hkeyboardhook != 0)
{
return unhookwindowshookex(hkeyboardhook);
}
return true;
}
}
}
上一篇: c#实现sqlserver事务处理示例
下一篇: gulp自动化构建工具