[C#.Net]全局鉤子實現USB掃碼槍無焦點狀態下掃入

1.掃描槍獲取數據原理基本至關於鍵盤數據,獲取掃描槍掃描出來的數據,通常分爲兩種實現方式。html

  a)文本框輸入獲取焦點,掃描後自動顯示在文本框內。數組

  b)使用鍵盤鉤子,勾取掃描槍虛擬按鍵,根據按鍵頻率進行手動輸入和掃描槍掃描判斷。緩存

2.要實現系統鉤子其實很簡單,調用三個Win32的API便可。函數

SetWindowsHookEx 用於設置鉤子。(設立一道卡子,盤查須要的信息)ui

CallNextHookEx 用於傳遞鉤子(消息是重要的,因此從哪裏來,就應該回到哪裏去,除非你決定要封鎖消息)spa

UnhookWindowsHookEx 卸載鉤子(卸載很重要,卡子設多了會形成擁堵)翻譯

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.Runtime.InteropServices;
  5 using System.Reflection;
  6 using System.Diagnostics;
  7 namespace SaomiaoTest2
  8 {
  9     /// <summary>
 10     /// 獲取鍵盤輸入或者USB掃描槍數據 能夠是沒有焦點 應爲使用的是全局鉤子
 11     /// USB掃描槍 是模擬鍵盤按下
 12     /// 這裏主要處理掃描槍的值,手動輸入的值不太好處理
 13     /// </summary>
 14    public class BardCodeHooK
 15     {
 16         public delegate void BardCodeDeletegate(BarCodes barCode);
 17         public event BardCodeDeletegate BarCodeEvent;
 18 
 19         //定義成靜態,這樣不會拋出回收異常
 20         private static HookProc hookproc;
 21 
 22 
 23         public struct BarCodes
 24         {
 25             public int VirtKey;//虛擬嗎
 26             public int ScanCode;//掃描碼
 27             public string KeyName;//鍵名
 28             public uint Ascll;//Ascll
 29             public char Chr;//字符
 30 
 31             public string BarCode;//條碼信息   保存最終的條碼
 32             public bool IsValid;//條碼是否有效
 33             public DateTime Time;//掃描時間,
 34         }
 35 
 36         private struct EventMsg
 37         {
 38             public int message;
 39             public int paramL;
 40             public int paramH;
 41             public int Time;
 42             public int hwnd;
 43         }
 44 
 45         [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
 46         private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
 47 
 48         [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
 49         private static extern bool UnhookWindowsHookEx(int idHook);
 50 
 51         [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
 52         private static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
 53 
 54         [DllImport("user32", EntryPoint = "GetKeyNameText")]
 55         private static extern int GetKeyNameText(int IParam, StringBuilder lpBuffer, int nSize);
 56 
 57         [DllImport("user32", EntryPoint = "GetKeyboardState")]
 58         private static extern int GetKeyboardState(byte[] pbKeyState);
 59 
 60         [DllImport("user32", EntryPoint = "ToAscii")]
 61         private static extern bool ToAscii(int VirtualKey, int ScanCode, byte[] lpKeySate, ref uint lpChar, int uFlags);
 62 
 63         [DllImport("kernel32.dll")]
 64         public static extern IntPtr GetModuleHandle(string name);
 65 
 66 
 67         delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
 68         BarCodes barCode = new BarCodes();
 69         int hKeyboardHook = 0;
 70         string strBarCode = "";
 71 
 72         private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
 73         {
 74             if (nCode == 0)
 75             {
 76                 EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg));
 77                 if (wParam == 0x100)//WM_KEYDOWN=0x100
 78                 {
 79                     barCode.VirtKey = msg.message & 0xff;//虛擬嗎
 80                     barCode.ScanCode = msg.paramL & 0xff;//掃描碼
 81                     StringBuilder strKeyName = new StringBuilder(225);
 82                     if (GetKeyNameText(barCode.ScanCode * 65536, strKeyName, 255) > 0)
 83                     {
 84                         barCode.KeyName = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
 85                     }
 86                     else
 87                     {
 88                         barCode.KeyName = "";
 89                     }
 90                     byte[] kbArray = new byte[256];
 91                     uint uKey = 0;
 92                     GetKeyboardState(kbArray);
 93 
 94 
 95                     if (ToAscii(barCode.VirtKey, barCode.ScanCode, kbArray, ref uKey, 0))
 96                     {
 97                         barCode.Ascll = uKey;
 98                         barCode.Chr = Convert.ToChar(uKey);
 99                     }
100 
101                     TimeSpan ts = DateTime.Now.Subtract(barCode.Time);
102 
103                     if (ts.TotalMilliseconds > 50)
104                     {//時間戳,大於50 毫秒錶示手動輸入
105                         strBarCode = barCode.Chr.ToString();
106                     }
107                     else
108                     {
109                         if ((msg.message & 0xff) == 13 && strBarCode.Length > 3)
110                         {//回車
111                             barCode.BarCode = strBarCode;
112                             barCode.IsValid = true;
113                         }
114                         strBarCode += barCode.Chr.ToString();
115                     }
116                     barCode.Time = DateTime.Now;
117                     if (BarCodeEvent != null)
118                         BarCodeEvent(barCode);//觸發事件
119                     barCode.IsValid = false;
120                 }
121             }
122             return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
123         }
124 
125         //安裝鉤子
126         public bool Start()
127         {
128             if (hKeyboardHook == 0)
129             {
130                 hookproc = new HookProc(KeyboardHookProc);
131 
132 
133                 //GetModuleHandle 函數 替代 Marshal.GetHINSTANCE
134                 //防止在 framework4.0中 註冊鉤子不成功
135                 IntPtr modulePtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
136 
137                 //WH_KEYBOARD_LL=13
138                 //全局鉤子 WH_KEYBOARD_LL
139                 //  hKeyboardHook = SetWindowsHookEx(13, hookproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
140 
141                 hKeyboardHook = SetWindowsHookEx(13, hookproc, modulePtr, 0);
142             }
143             return (hKeyboardHook != 0);
144         }
145 
146         //卸載鉤子
147         public bool Stop()
148         {
149             if (hKeyboardHook != 0)
150             {
151                 return UnhookWindowsHookEx(hKeyboardHook);
152             }
153             return true;
154         }
155     }
156 }

在實踐過程當中,發現版本一的代碼只能掃描條形碼,如伴隨二維碼中的字母出現就不能正確獲取數據。指針

版本二:code

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace BarcodeScanner
{
    public class ScanerHook
    {
        public delegate void ScanerDelegate(ScanerCodes codes);
        public event ScanerDelegate ScanerEvent;

       //private const int WM_KEYDOWN = 0x100;//KEYDOWN
              //private const int WM_KEYUP = 0x101;//KEYUP
              //private const int WM_SYSKEYDOWN = 0x104;//SYSKEYDOWN
              //private const int WM_SYSKEYUP = 0x105;//SYSKEYUP
//private static int HookProc(int nCode, Int32 wParam, IntPtr lParam);
        private int hKeyboardHook = 0;//聲明鍵盤鉤子處理的初始值
        private ScanerCodes codes = new ScanerCodes();//13爲鍵盤鉤子
        //定義成靜態,這樣不會拋出回收異常
        private static HookProc hookproc;
        delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
        [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")]
      //ToAscii職能的轉換指定的虛擬鍵碼和鍵盤狀態的相應字符或字符
        private static extern bool ToAscii(int VirtualKey, int ScanCode, byte[] lpKeySate, ref uint lpChar, int uFlags);
    
      //int VirtualKey //[in] 指定虛擬關鍵代碼進行翻譯。
      //int uScanCode, // [in] 指定的硬件掃描碼的關鍵須翻譯成英文。高階位的這個值設定的關鍵,若是是(不壓)
      //byte[] lpbKeyState, // [in] 指針,以256字節數組,包含當前鍵盤的狀態。每一個元素(字節)的數組包含狀態的一個關鍵。若是高階位的字節是一套,關鍵是下跌(按下)。在低比特,如/果設置代表,關鍵是對切換。在此功能,只有肘位的CAPS LOCK鍵是相關的。在切換狀態的NUM個鎖和滾動鎖定鍵被忽略。
      //byte[] lpwTransKey, // [out] 指針的緩衝區收到翻譯字符或字符。
      //uint fuState); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.

        
            
        [DllImport("kernel32.dll")]
     //使用WINDOWS API函數代替獲取當前實例的函數,防止鉤子失效
        public static extern IntPtr GetModuleHandle(string name);
        public ScanerHook()
        {
        }
        public bool Start()
        {
            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);
        }
        public bool Stop()
        {
            if (hKeyboardHook != 0)
            {
               bool  retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
                hKeyboardHook = 0;
                return retKeyboard;
               
            }
            return true;
        }
        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
           
          
            EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg));
            codes.Add(msg);
            if (ScanerEvent != null && msg.message == 13 && msg.paramH > 0 && !string.IsNullOrEmpty(codes.Result))
            {
                ScanerEvent(codes);
            }
             return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
        }
        public class ScanerCodes
        {
            private int ts = 100; // 指定輸入間隔爲300毫秒之內時爲連續輸入  
            private List<List<EventMsg>> _keys = new List<List<EventMsg>>();
            private List<int> _keydown = new List<int>();   // 保存組合鍵狀態  
            private List<string> _result = new List<string>();  // 返回結果集  
            private DateTime _last = DateTime.Now;
            private byte[] _state = new byte[256];
            private string _key = string.Empty;
            private string _cur = string.Empty;
            public EventMsg Event
            {
                get
                {
                    if (_keys.Count == 0)
                    {
                        return new EventMsg();
                    }
                    else
                    {
                        return _keys[_keys.Count - 1][_keys[_keys.Count - 1].Count - 1];
                    }
                }
            }
            public List<int> KeyDowns
            {
                get
                {
                    return _keydown;
                }
            }
            public DateTime LastInput
            {
                get
                {
                    return _last;
                }
            }
            public byte[] KeyboardState
            {
                get
                {
                    return _state;
                }
            }
            public int KeyDownCount
            {
                get
                {
                    return _keydown.Count;
                }
            }
            public string Result
            {
                get
                {
                    if (_result.Count > 0)
                    {
                        return _result[_result.Count - 1].Trim();
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            public string CurrentKey
            {
                get
                {
                    return _key;
                }
            }
            public string CurrentChar
            {
                get
                {
                    return _cur;
                }
            }
            public bool isShift
            {
                get
                {
                    return _keydown.Contains(160);
                }
            }
            public void Add(EventMsg msg)
            {
                #region 記錄按鍵信息           

                // 首次按下按鍵  
                if (_keys.Count == 0)
                {
                    _keys.Add(new List<EventMsg>());
                    _keys[0].Add(msg);
                    _result.Add(string.Empty);
                }
                // 未釋放其餘按鍵時按下按鍵  
                else if (_keydown.Count > 0)
                {
                    _keys[_keys.Count - 1].Add(msg);
                }
                // 單位時間內按下按鍵  
                else if (((TimeSpan)(DateTime.Now - _last)).TotalMilliseconds < ts)
                {
                    _keys[_keys.Count - 1].Add(msg);
                }
                // 重新記錄輸入內容  
                else
                {
                    _keys.Add(new List<EventMsg>());
                    _keys[_keys.Count - 1].Add(msg);
                    _result.Add(string.Empty);
                }
                #endregion
                _last = DateTime.Now;
                #region 獲取鍵盤狀態
                // 記錄正在按下的按鍵  
                if (msg.paramH == 0 && !_keydown.Contains(msg.message))
                {
                    _keydown.Add(msg.message);
                }
                // 清除已鬆開的按鍵  
                if (msg.paramH > 0 && _keydown.Contains(msg.message))
                {
                    _keydown.Remove(msg.message);
                }
                #endregion
                #region 計算按鍵信息
            
               int v = msg.message & 0xff;
                int c = msg.paramL & 0xff;
                StringBuilder strKeyName = new StringBuilder(500);
                if (GetKeyNameText(c * 65536, strKeyName, 255) > 0)
                {
                    _key = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
                    GetKeyboardState(_state);
                    if (_key.Length == 1 && msg.paramH == 0)// && msg.paramH == 0
                    {
                        // 根據鍵盤狀態和shift緩存判斷輸出字符  
                        _cur = ShiftChar(_key, isShift, _state).ToString();
                        _result[_result.Count - 1] += _cur;
                    }
              // 備選
             else
                    {
                        _cur = string.Empty;
                    }
                }
                #endregion
            }
            private char ShiftChar(string k, bool isShiftDown, byte[] state)
            {
                bool capslock = state[0x14] == 1;
                bool numlock = state[0x90] == 1;
                bool scrolllock = state[0x91] == 1;
                bool shiftdown = state[0xa0] == 1;
                char chr = (capslock ? k.ToUpper() : k.ToLower()).ToCharArray()[0];
                if (isShiftDown)
                {
                    if (chr >= 'a' && chr <= 'z')
                    {
                     chr = (char)((int)chr - 32);
                    }
                    else if (chr >= 'A' && chr <= 'Z')
                    {
                        if (chr=='Z')
                        {
                            string s = "";
                        }
                        chr = (char)((int)chr + 32);
                    }                   
                    else
                    {                      
                        string s = "`1234567890-=[];',./";
                        string u = "~!@#$%^&*()_+{}:\"<>?";
                        if (s.IndexOf(chr) >= 0)
                        {
                            return (u.ToCharArray())[s.IndexOf(chr)];
                        }
                    }
                }
                return chr;
            }
        }
        public struct EventMsg
        {
            public int message;
            public int paramL;
            public int paramH;
            public int Time;
            public int hwnd;
        }
    }
}

版本二中的代碼,實踐中發現出現了獲取掃描數據卻省略「+」加號的狀況出現。orm

所以在版本二中備選處添加

//判斷是+ 強制添加+
                    else if (_key.Length == 5 && msg.paramH == 0&&msg.paramL==78&&msg.message==107)// && msg.paramH == 0
                    {
                        // 根據鍵盤狀態和shift緩存判斷輸出字符  
                        _cur = Convert.ToChar('+').ToString();
                        _result[_result.Count - 1] += _cur;
                    }

3.winform在無焦點狀況下的使用方式:

using BarcodeScanner;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BarCodeTest
{
    public partial class Form1 : Form
    {
        private ScanerHook listener = new ScanerHook();  
        public Form1()
        {
            InitializeComponent();
            listener.ScanerEvent += Listener_ScanerEvent;  
        }
        private void Listener_ScanerEvent(ScanerHook.ScanerCodes codes)
        {
            textBox3.Text = codes.Result;         
        }  
        private void Form1_Load(object sender, EventArgs e)
        {
            listener.Start();  
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            listener.Stop();  
        }  
    }
}

其實上面的代碼都是複製這位大俠的,真心以爲大俠太厲害了,解決多年的疑惑,保留記念

https://www.cnblogs.com/TBW-Superhero/p/8659306.html

相關文章
相關標籤/搜索