为何发生ERROR_INVALID_HOOK_HANDLE

时间:2014-02-05 05:33:29

标签: c#

  

错误名称:ERROR_INVALID_HOOK_HANDLE

     

错误代码:1404(0x57C)

     

描述:钩子句柄无效。

我的问题是:

1)有人知道上述系统错误代码何时发生?

2)UnhookWindowsHookEx()函数能否导致上述系统代码?

我一直在谷歌搜索。但是,我找不到任何肯定的答案。 拜托,有人帮助我。

实际上,我正在开发一个与其他机器进行远程连接的应用程序。 该应用程序还监视用户在远程计算机上执行的操作。

为了监控用户的操作,我在连接到远程机器时为WH_KEYBOARD_LL和WH_MOUSE_LL挂钩安装了自定义挂钩程序。我使用SetWindowsHookEx()方法安装了钩子程序。

以下代码包括WH_KEYBOARD_LL的自定义挂钩过程定义,并将该挂钩过程安装到WH_KEYBOARD_LL挂钩的挂钩链。

// custom keyboard hook procedure
private static int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
    {
        //indicates if any of underlaing events set e.Handled flag
        bool handled = false;

        if (nCode >= 0)
        {
            //read structure KeyboardHookStruct at lParam
            KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
            //raise KeyDown
            if (s_KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
            {
                Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode;
                KeyEventArgs e = new KeyEventArgs(keyData);
                s_KeyDown.Invoke(null, e);
                handled = e.Handled;
            }

            // raise KeyPress
            if (s_KeyPress != null && wParam == WM_KEYDOWN)
            {
                bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false);
                bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false);

                byte[] keyState = new byte[256];
                GetKeyboardState(keyState);
                byte[] inBuffer = new byte[2];
                if (ToAscii(MyKeyboardHookStruct.VirtualKeyCode,
                          MyKeyboardHookStruct.ScanCode,
                          keyState,
                          inBuffer,
                          MyKeyboardHookStruct.Flags) == 1)
                {
                    char key = (char)inBuffer[0];
                    if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key);
                    KeyPressEventArgs e = new KeyPressEventArgs(key);
                    s_KeyPress.Invoke(null, e);
                    handled = handled || e.Handled;
                }
            }

            // raise KeyUp
            if (s_KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
            {
                Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode;
                KeyEventArgs e = new KeyEventArgs(keyData);
                s_KeyUp.Invoke(null, e);
                handled = handled || e.Handled;
            }

        }

        //if event handled in application do not handoff to other listeners
        if (handled)
            return -1;

        //forward to other application
        return CallNextHookEx(s_KeyboardHookHandle, nCode, wParam, lParam);
    }

// installing keyboard hook procedure
private static void EnsureSubscribedToGlobalKeyboardEvents()
    {
        // install Keyboard hook only if it is not installed and must be installed
        if (s_KeyboardHookHandle == 0)
        {
            //See comment of this field. To avoid GC to clean it up.
            s_KeyboardDelegate = KeyboardHookProc;
            //install hook
            s_KeyboardHookHandle = SetWindowsHookEx(
                WH_KEYBOARD_LL,
                s_KeyboardDelegate,
                Marshal.GetHINSTANCE(
                    Assembly.GetExecutingAssembly().GetModules()[0]),
                0);
            //If SetWindowsHookEx fails.
            if (s_KeyboardHookHandle == 0)
            {
                //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
                int errorCode = Marshal.GetLastWin32Error();
                //do cleanup

                //Initializes and throws a new instance of the Win32Exception class with the specified error. 
                throw new Win32Exception(errorCode);
            }
        }
    }

以下代码包括WH_MOUSE_LL的自定义挂钩过程定义,并将该挂钩过程安装到WH_MOUSE_LL挂钩的挂钩链。

// custom mouse hook procedure
private static int MouseHookProc(int nCode, int wParam, IntPtr lParam)
    {
        if (nCode >= 0)
        {
            //Marshall the data from callback.
            MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));

            //detect button clicked
            MouseButtons button = MouseButtons.None;
            short mouseDelta = 0;
            int clickCount = 0;
            bool mouseDown = false;
            bool mouseUp = false;

            switch (wParam)
            {
                case WM_LBUTTONDOWN:
                    mouseDown = true;
                    button = MouseButtons.Left;
                    clickCount = 1;
                    break;
                case WM_LBUTTONUP:
                    mouseUp = true;
                    button = MouseButtons.Left;
                    clickCount = 1;
                    break;
                case WM_LBUTTONDBLCLK: 
                    button = MouseButtons.Left;
                    clickCount = 2;
                    break;
                case WM_RBUTTONDOWN:
                    mouseDown = true;
                    button = MouseButtons.Right;
                    clickCount = 1;
                    break;
                case WM_RBUTTONUP:
                    mouseUp = true;
                    button = MouseButtons.Right;
                    clickCount = 1;
                    break;
                case WM_RBUTTONDBLCLK: 
                    button = MouseButtons.Right;
                    clickCount = 2;
                    break;
                case WM_MOUSEWHEEL:
                    //If the message is WM_MOUSEWHEEL, the high-order word of MouseData member is the wheel delta. 
                    //One wheel click is defined as WHEEL_DELTA, which is 120. 
                    //(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value
                    mouseDelta = (short)((mouseHookStruct.MouseData >> 16) & 0xffff);

                //TODO: X BUTTONS (I havent them so was unable to test)
                    //If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP, 
                    //or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released, 
                    //and the low-order word is reserved. This value can be one or more of the following values. 
                    //Otherwise, MouseData is not used. 
                    break;
            }

            //generate event 
            MouseEventExtArgs e = new MouseEventExtArgs(
                                               button,
                                               clickCount,
                                               mouseHookStruct.Point.X,
                                               mouseHookStruct.Point.Y,
                                               mouseDelta);

            //Mouse up
            if (s_MouseUp!=null && mouseUp)
            {
                s_MouseUp.Invoke(null, e);
            }

            //Mouse down
            if (s_MouseDown != null && mouseDown)
            {
                s_MouseDown.Invoke(null, e);
            }

            //If someone listens to click and a click is heppened
            if (s_MouseClick != null && clickCount>0)
            {
                s_MouseClick.Invoke(null, e);
            }

            //If someone listens to click and a click is heppened
            if (s_MouseClickExt != null && clickCount > 0)
            {
                s_MouseClickExt.Invoke(null, e);
            }

            //If someone listens to double click and a click is heppened
            if (s_MouseDoubleClick != null && clickCount == 2)
            {
                s_MouseDoubleClick.Invoke(null, e);
            }

            //Wheel was moved
            if (s_MouseWheel!=null && mouseDelta!=0)
            {
                s_MouseWheel.Invoke(null, e);
            }

            //If someone listens to move and there was a change in coordinates raise move event
            if ((s_MouseMove!=null || s_MouseMoveExt!=null) && (m_OldX != mouseHookStruct.Point.X || m_OldY != mouseHookStruct.Point.Y))
            {
                m_OldX = mouseHookStruct.Point.X;
                m_OldY = mouseHookStruct.Point.Y;
                if (s_MouseMove != null)
                {
                    s_MouseMove.Invoke(null, e);
                }

                if (s_MouseMoveExt != null)
                {
                    s_MouseMoveExt.Invoke(null, e);
                }
            }

            if (e.Handled)
            {
                return -1;
            }
        }

        //call next hook
        return CallNextHookEx(s_MouseHookHandle, nCode, wParam, lParam);
    }

// installing mouse hook procedure
private static void EnsureSubscribedToGlobalMouseEvents()
    {
        // install Mouse hook only if it is not installed and must be installed
        if (s_MouseHookHandle == 0)
        {
            //See comment of this field. To avoid GC to clean it up.
            s_MouseDelegate = MouseHookProc;
            //install hook
            s_MouseHookHandle = SetWindowsHookEx(
                WH_MOUSE_LL,
                s_MouseDelegate,
                Marshal.GetHINSTANCE(
                    Assembly.GetExecutingAssembly().GetModules()[0]),
                0);
            //If SetWindowsHookEx fails.
            if (s_MouseHookHandle == 0)
            {
                //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
                int errorCode = Marshal.GetLastWin32Error();
                //do cleanup

                //Initializes and throws a new instance of the Win32Exception class with the specified error. 
                throw new Win32Exception(errorCode);
            }
        }
    }

当用户从目标服务器断开连接时,我必须再次卸载这些挂钩程序。

以下是卸载WH_KEYBOARD_LL和WH_MOUSE_LL挂钩的挂钩程序的代码。

// uninstalling custom mouse hook procedure
private static void ForceUnsunscribeFromGlobalMouseEvents()
    {
        if (s_MouseHookHandle != 0)
        {
            //uninstall hook
            int result = UnhookWindowsHookEx(s_MouseHookHandle);
            //reset invalid handle
            s_MouseHookHandle = 0;
            //Free up for GC
            s_MouseDelegate = null;
            //if failed and exception must be thrown
            if (result == 0)
            {
                //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
                int errorCode = Marshal.GetLastWin32Error();
                //Initializes and throws a new instance of the Win32Exception class with the specified error. 
                throw new Win32Exception(errorCode);
            }
        }
    }

//uninstalling custom keyboard hook procedure
private static void ForceUnsunscribeFromGlobalKeyboardEvents()
    {
        if (s_KeyboardHookHandle != 0)
        {
            //uninstall hook
            int result = UnhookWindowsHookEx(s_KeyboardHookHandle);
            //reset invalid handle
            s_KeyboardHookHandle = 0;
            //Free up for GC
            s_KeyboardDelegate = null;
            //if failed and exception must be thrown
            if (result == 0)
            {
                //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
                int errorCode = Marshal.GetLastWin32Error();
                //Initializes and throws a new instance of the Win32Exception class with the specified error. 
                throw new Win32Exception(errorCode);
            }
        }
    }

当我卸载钩子程序时,我有时会得到Marshal.GetLastWin32Error()返回的ERROR_INVALID_HOOK_HANDLE错误。但不总是。 我真的对此没有任何想法。所以,我试着在这篇文章中询问ERROR_INVALID_HOOK_HANDLE错误。

0 个答案:

没有答案