c#使用鉤子函數會出現字母重複和和少最後一個字符的問題

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Windows.Forms;
using static ReadBadCode.BarCodeHook;

namespace 希立儀器
{
    class BarCodeHook
    {
        public delegate void BarCodeDelegate(BarCodes barCode);
        public static event BarCodeDelegate BarCodeEvent;
        public struct BarCodes
        {
            public int VirtKey;  //虛擬碼
            public int ScanCode;  //掃描碼
            public string KeyName; //鍵名
            public uint AscII;  //AscII
            public char Chr;   //字符
            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);
        //獲取鍵名的字符串
        [DllImport("user32", EntryPoint = "GetKeyNameText")]
        private static extern int GetKeyNameText(int lParam, StringBuilder lpBuffer, int nSize);
        //將256個虛擬鍵複製到指定的緩衝區中
        [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[] lpKeyState, ref uint lpChar, int uFlags);
        //聲明定義回調函數
        delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);

        private static BarCodes barCode = new BarCodes();
        private static int hKeyboardHook = 0;
        private static string strBarCode = "";
        private static 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; //掃描碼
                    StringBuilder strKeyName = new StringBuilder(255);
                    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);

                        /*有斜槓行的下面第二部分放到這裏就不會出現重複字母,

                         *還有少字符是因爲上面第一部分和下面第二部分位置對調了

                          */
                        ////////////////////////////第二部分///////////
                        if (DateTime.Now.Subtract(barCode.Time).TotalMilliseconds > 50)
                        {
                            strBarCode = barCode.Chr.ToString();
                        }
                        else
                        {
                            if ((msg.message & 0xff) == 13 && strBarCode.Length > 3)
                            //回車
                            {
                                barCode.BarCode = strBarCode;
                                barCode.IsValid = true;
                            }
                            strBarCode += barCode.Chr.ToString();
                        }
                        barCode.Time = DateTime.Now;
                        ///////////////////////////////////////

                    }

                    if (BarCodeEvent != null) BarCodeEvent(barCode);
                    //觸發事件
                    barCode.IsValid = false;
                }
            }
            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;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章