C# 为什么会发生错误\u无效\u钩子\u句柄

C# 为什么会发生错误\u无效\u钩子\u句柄,c#,C#,错误名称:错误\u无效\u钩子\u句柄 错误代码:1404 0x57C 描述:无效的钩子句柄 我的问题是: 1是否有人知道上述系统错误代码何时发生 2 UnhookWindowsHookEx函数是否会导致上述系统代码 我一直在用谷歌搜索。但是,我找不到任何确切的答案。 求求你,谁来帮帮我 实际上,我正在开发一个可以远程连接到其他机器的应用程序。 该应用程序还监视用户在远程机器上的操作 为了监视用户的操作,我在连接到远程机器时为WHU键盘和WHU鼠标钩子安装了自定义钩子过程。我使用SetWindo

错误名称:错误\u无效\u钩子\u句柄

错误代码:1404 0x57C

描述:无效的钩子句柄

我的问题是:

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

2 UnhookWindowsHookEx函数是否会导致上述系统代码

我一直在用谷歌搜索。但是,我找不到任何确切的答案。 求求你,谁来帮帮我

实际上,我正在开发一个可以远程连接到其他机器的应用程序。 该应用程序还监视用户在远程机器上的操作

为了监视用户的操作,我在连接到远程机器时为WHU键盘和WHU鼠标钩子安装了自定义钩子过程。我使用SetWindowsHookEx方法安装了钩子过程

以下代码包括WHU键盘挂钩的自定义挂钩过程定义,以及将该挂钩过程安装到WHU键盘挂钩的挂钩链

// 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 hook的钩子链

// 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_键盘和WH_鼠标钩子的钩子过程的代码

// 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);
            }
        }
    }
当我卸载钩子过程时,我得到了错误\u无效\u钩子\u句柄错误,Marshal.GetLastWin32Error有时返回错误。但并非总是如此。
我真的没有任何想法。因此,我试图在这篇文章中询问错误\u无效\u钩子\u处理错误。

上下文是什么?你想干什么?给我们看一些代码。你在哪里使用它?你在操纵注册表吗?共享更多信息以获得更好的答案。句柄是IntPtr,而不是int。因此,此代码在64位操作系统上可能会失败。在.NET 4.0及更高版本上,使用Marshal.GetHINSTANCE不再可靠。仅当您以.NET 3.5为目标并强制程序以32位模式运行时才使用此代码。因此,对于处理程序,它应该是IntPtr而不是int。对于Marshal.GetHINSTANCE,我应该使用什么来代替它。我的应用程序将在.NET3.5和WindowsServer2008R2 64位上运行