低级键盘挂钩自动安装并减慢计算机速度?

时间:2013-01-26 18:54:54

标签: c# desktop-application keyboard-hook

我在桌面应用程序中使用Keyboard Low Level挂钩来监控用户活动。我用于钩子的代码如下。 在这段代码中(据我所知),当我必须开始监视用户活动时,我调用SetHook()这将安装钩子,我可以监视键盘上按下的键。当我想停止捕获键时,我只需要调用UnHook()方法。

问题是当我的应用程序启动时(SetHook()方法尚未调用)我的应用程序安装会自动挂钩并且会降低系统速度。系统每1分钟挂起2-3秒。

为了诊断问题,我注释掉了下面提到的所有代码和已安装的应用程序。现在系统工作正常。

我不确定为什么会这样?

  1. 为什么我的应用程序开始捕获密钥,即​​使我还没有调用SetHook()方法呢?
  2. 是否有其他方法可以在不使用挂钩的情况下捕获全局密钥?
  3. 钩子代码:

    public static class WinKeyCapture5   {
    
       private const int WH_KEYBOARD_LL = 13;
       private const int WM_KEYDOWN = 0x0100;
       private static LowLevelKeyboardProc _proc = HookCallback;
       public static DateTime LastKeyPressTime;
    
       public static void SetHook()
       {
           SetHook(_proc);
       }
    
       public static void UnHook()
       {
           UnhookWindowsHookEx(_hookID);
       }
    
       private static IntPtr SetHook(LowLevelKeyboardProc proc)
       {
           using (Process curProcess = Process.GetCurrentProcess())
           using (ProcessModule curModule = curProcess.MainModule)
           {
               return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
           }
       }
    
       private static IntPtr _hookID = IntPtr.Zero;
    
       private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
    
       private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
       {
           //if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
           //{
               int vkCode = Marshal.ReadInt32(lParam);
               //if (vkCode == 44)
                   //ScreenCapture.Load();
    
    
    
               LastKeyPressTime = System.DateTime.Now;
    
    
           //}
    
           return CallNextHookEx(_hookID, nCode, wParam, lParam);
       }
       [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
       private static extern IntPtr SetWindowsHookEx(int idHook,
           LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
       [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
       [return: MarshalAs(UnmanagedType.Bool)]
       private static extern bool UnhookWindowsHookEx(IntPtr hhk);
       [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
       private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
           IntPtr wParam, IntPtr lParam);
       [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
       private static extern IntPtr GetModuleHandle(string lpModuleName); 
    }
    

0 个答案:

没有答案