Example of getting barcode gun return value without focus
- 2020-06-01 10:53:21
- OfStack
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; // Virtual code
public int ScanCode; // Scan code
public string BarCode; // The barcode information
public bool IsValid; // Whether the bar code is valid
public DateTime Time; // Sweep 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; // Virtual code
barCode.ScanCode = msg.paramL & 0xff; // Scan code
if (DateTime.Now.Subtract(barCode.Time).TotalMilliseconds > 100)
{
_barcode.Clear();
}
else
{
if ((msg.message & 0xff) == 13 && _barcode.Count > 0) // enter
{
barCode.BarCode = new String(_barcode.ToArray());
barCode.IsValid = true;
_barcode.Clear();
}
}
barCode.Time = DateTime.Now;
if (BarCodeEvent != null) BarCodeEvent(barCode); // Triggering event
barCode.IsValid = false;
_barcode.Add(Convert.ToChar(msg.message & 0xff));
}
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
private static HookProc hookproc;
// Install hooks
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);
}
// Uninstall hooks
public bool Stop()
{
if (hKeyboardHook != 0)
{
return UnhookWindowsHookEx(hKeyboardHook);
}
return true;
}
}
}