<summary>////Get keyboard input or USB scan gun data can be no focus should be used is the global hook///USB scan gun is analog keyboard pressed///here the main processing of the value of the scanner, manual input value is not very good processing// </summary> public class Bardcodehook {public delegate void Bardcodedeletegate (barcodes barCode); public event Bardcodedeletegate Barcodeevent; defined as static, which does not throw a reclaim exception to the private static HookProc HookProc; Public struct Barcodes {public int virtkey;//virtual public int scancode;//Scan Code Public String keyname;//key name public uint ASCLL;//ASCLL Public Char chr;//character public string Origina lchrs; Original character public string originalasciis;//original ASCII public string Originalbarcode; The original data bar code public bool isvalid;//bar code is valid public DateTime time;//scan time, public string BarCode; Barcode Information Save the final barcode} 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 s tatic extern int SetWindowsHookEx (int idhook, HookProc lpfn, IntPtr hinstance, int threadId); [DllImport ("user32.dll", CharSet = CharSet.Auto, callingconvention = callingconvention.stdcall)] private static ext ern bool UnhookWindowsHookEx (int idhook); [DllImport ("user32.dll", CharSet = CharSet.Auto, callingconvention = callingconvention.stdcall)] private static ext ern int CallNextHookEx (int idhook, int nCode, Int32 wParam, IntPtr lParam); [DllImport ("user32", EntryPoint = "Getkeynametext")] private static extern int Getkeynametext (int iparam, Stringbui Lder 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")] public static extern IntPtr GetModuleHandle (string name); delegate int HookProc (int nCode, Int32 wParam, IntPtr lParam); Barcodes BarCode = new Barcodes (); int hkeyboardhook = 0; String strbarcode = ""; StringBuilder Sbbarcode = new StringBuilder (); private 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 &A mp 0xff;//virtual? barcode.scancode = msg.paraml & 0xff;//Scan code StringBuilder strkeyname = New StringBuilder (225); if (GetkeynamEText (Barcode.scancode * 65536, Strkeyname, 255) > 0) {barcode.keyname = str Keyname.tostring (). Trim (new char[] {', ' +} '); } else {barcode.keyname = ""; } byte[] Kbarray = new byte[256]; UINT Ukey = 0; Getkeyboardstate (Kbarray); if (BarCode.KeyName.Equals ("a") | | | barCode.KeyName.Equals ("a"))//{if (Toasci I (Barcode.virtkey, Barcode.scancode, Kbarray, ref ukey, 0)) {BARCODE.ASCLL = UK ey BARCODE.CHR = Convert.tochar (Ukey); barcode.originalchrs + = "" + convert.tostring (BARCODE.CHR); Barcode.originalasciis + = "" + convert.tostring (BARCODE.ASCLL); Barcode.originalbarcode + = convert.tostring(BARCODE.CHR); }//} TimeSpan ts = DateTime.Now.Subtract (barcode.time); if (TS. TotalMilliseconds > 30) {//timestamp, greater than 50 ms means manual input//Strbarcode = BarCode.Chr.ToSt Ring (); Sbbarcode.remove (0, sbbarcode.length); Sbbarcode.append (BarCode.Chr.ToString ()); barcode.originalchrs = "" + convert.tostring (BARCODE.CHR); Barcode.originalasciis = "" + convert.tostring (BARCODE.ASCLL); Barcode.originalbarcode = convert.tostring (BARCODE.CHR); } else {if ((Msg.message & 0xff) = = && Sbbarc Ode. Length > 3) {//Enter//Barcode.barcode = Strbarcode; Barcode.barcode = Sbbarcode.tostring (); Barcode.barcode = Barcode.originalbarcode; Barcode.isvalid = true; Strbarcode = ""; Sbbarcode.remove (0, sbbarcode.length); }////strbarcode + = barCode.Chr.ToString ();//Updated by Dragon 20141124 Sbbarcode.append (BarCode.Chr.ToString ()); Strbarcode + = Barcode.keyname; Strbarcode + = barCode.VirtKey.ToString (); } try {if (barcodeevent! = null && barcode.isvalid) {//barcode.barcode = barCode.BarCode.Replace ("\b", "" "). Replace ("n", ""); Can not be required because more than 50 milliseconds have been processed//first Windows events are passed I_callednext = CallNextHookEx ( Hkeyboardhook, NCode, WParam, LParam); Barcodeevent (BarCode);//trigger Event Barcode.barcode = ""; barcode.originalchrs = ""; Barcode.originalasciis = ""; Barcode.originalbarcode = ""; }} catch {} finally { Barcode.isvalid = false; Finally, be sure to set barCode invalid barcode.time = DateTime.Now; }}} if (I_callednext = = -10) {I_callednext = Callnexthoo KEx (Hkeyboardhook, NCode, WParam, LParam); } return i_callednext; }//install hook public bool Start () {if (Hkeyboardhook = = 0) {Hookpro c = new HookProc (KEYBOARDHOOKPROC); GetModuleHandle function substitution marshal.gethinstance//Prevent registration of hooks in framework4.0 unsuccessful IntPtr moduleptr = GetModuleHandle (Process.getcurrentprocess (). Mainmodule.modulename); WH_KEYBOARD_LL=13//Global hook wh_keyboard_ll//Hkeyboardhook = SetWindowsHookEx (HookProc, Marshal.gethinstance (assembly.getexecutingassembly (). GetModules () [0]), 0); Hkeyboardhook = SetWindowsHookEx (HookProc, moduleptr, 0); } return (Hkeyboardhook! = 0); }//Unload Hook public bool Stop () {if (Hkeyboardhook! = 0) {return U Nhookwindowshookex (Hkeyboardhook); } return true; } }
Page usage:
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: "";//is the scanner input, if true, otherwise keyboard input
Textbox7.text + = Barcode.keyname;
MessageBox.Show (BarCode.IsValid.ToString ());
}
}
Scan gun input and keyboard input in C #
Private DateTime _dt = DateTime.Now; Define a member function to hold a point in time for each
private void Textbox1_keypress (object sender, KeyPressEventArgs e)
//{
DateTime TEMPDT = DateTime.Now; Save the button at the point in time
TimeSpan ts = TEMPDT. Subtract (_DT); Get time interval
if (Ts.milliseconds > 50)//judgment interval, if the time interval is greater than 50 milliseconds, the TextBox will be emptied
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 ("Barcode Length:" + textBox6.Text.Length + "\ n Barcode Content:" + textbox6.text, "system hint");
}
}
}
}
Reprint: http://www.cnblogs.com/Hdsome/archive/2011/11/15/2227717.html
Get keyboard input or USB scan gun data