Call has been made on garbage collected delegate in C#?

匿名 (未验证) 提交于 2019-12-03 01:30:01

问题:

I have been using this key hook script i found but I continue to get an error after a few seconds of using it in my program. The error says.. A call has been made on a garbage collected delegate 'keylogger!Utilities.globalKeyboardHook+keyboardHookProc::Invoke'.

How can I fix this?

namespace Utilities { ///  /// A class that manages a global low level keyboard hook ///  class globalKeyboardHook {      #region Constant, Structure and Delegate Definitions     ///      /// defines the callback type for the hook     ///      public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);      public struct keyboardHookStruct     {         public int vkCode;         public int scanCode;         public int flags;         public int time;         public int dwExtraInfo;     }      const int WH_KEYBOARD_LL = 13;     const int WM_KEYDOWN = 0x100;     const int WM_KEYUP = 0x101;     const int WM_SYSKEYDOWN = 0x104;     const int WM_SYSKEYUP = 0x105;     #endregion      #region Instance Variables     ///      /// The collections of keys to watch for     ///      public List HookedKeys = new List();     ///      /// Handle to the hook, need this to unhook and call the next hook     ///      IntPtr hhook = IntPtr.Zero;     #endregion      #region Events     ///      /// Occurs when one of the hooked keys is pressed     ///      public event KeyEventHandler KeyDown;     ///      /// Occurs when one of the hooked keys is released     ///      public event KeyEventHandler KeyUp;     #endregion      #region Constructors and Destructors     ///      /// Initializes a new instance of the  class and installs the keyboard hook.     ///      public globalKeyboardHook()     {         hook();     }      ///      /// Releases unmanaged resources and performs other cleanup operations before the     ///  is reclaimed by garbage collection and uninstalls the keyboard hook.     ///      ~globalKeyboardHook()     {         unhook();     }     #endregion      #region Public Methods     ///      /// Installs the global hook     ///      public void hook()     {          IntPtr hInstance = LoadLibrary("User32");         hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);     }      ///      /// Uninstalls the global hook     ///      public void unhook()     {         UnhookWindowsHookEx(hhook);     }      ///      /// The callback for the keyboard hook     ///      /// The hook code, if it isn't >= 0, the function shouldn't do anyting     /// The event type     /// The keyhook event information     ///      public int hookProc(int code, int wParam, ref keyboardHookStruct lParam)     {         if (code >= 0)         {             Keys key = (Keys)lParam.vkCode;             if (HookedKeys.Contains(key))             {                 KeyEventArgs kea = new KeyEventArgs(key);                 if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null))                 {                     KeyDown(this, kea);                 }                 else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null))                 {                     KeyUp(this, kea);                 }                 if (kea.Handled)                     return 1;             }         }         return CallNextHookEx(hhook, code, wParam, ref lParam);     }     #endregion      #region DLL imports     ///      /// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null     ///      /// The id of the event you want to hook     /// The callback.     /// The handle you want to attach the event to, can be null     /// The thread you want to attach the event to, can be null     /// a handle to the desired hook     [DllImport("user32.dll")]     static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);      ///      /// Unhooks the windows hook.     ///      /// The hook handle that was returned from SetWindowsHookEx     /// True if successful, false otherwise     [DllImport("user32.dll")]     static extern bool UnhookWindowsHookEx(IntPtr hInstance);      ///      /// Calls the next hook.     ///      /// The hook id     /// The hook code     /// The wparam.     /// The lparam.     ///      [DllImport("user32.dll")]     static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);      ///      /// Loads the library.     ///      /// Name of the library     /// A handle to the library     [DllImport("kernel32.dll")]     static extern IntPtr LoadLibrary(string lpFileName);     #endregion     } } 

globalKeyboardHook class :

using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Windows.Forms; using System.IO;  namespace Utilities { ///  /// A class that manages a global low level keyboard hook ///  class globalKeyboardHook : IDisposable {      private bool _disposed;      #region Constant, Structure and Delegate Definitions     ///      /// defines the callback type for the hook     ///      public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);      public struct keyboardHookStruct     {         public int vkCode;         public int scanCode;         public int flags;         public int time;         public int dwExtraInfo;     }      const int WH_KEYBOARD_LL = 13;     const int WM_KEYDOWN = 0x100;     const int WM_KEYUP = 0x101;     const int WM_SYSKEYDOWN = 0x104;     const int WM_SYSKEYUP = 0x105;     #endregion      #region Instance Variables     ///      /// The collections of keys to watch for     ///      public List HookedKeys = new List();     ///      /// Handle to the hook, need this to unhook and call the next hook     ///      IntPtr hhook = IntPtr.Zero;     #endregion      #region Events     ///      /// Occurs when one of the hooked keys is pressed     ///      public event KeyEventHandler KeyDown;     ///      /// Occurs when one of the hooked keys is released     ///      public event KeyEventHandler KeyUp;     #endregion      #region Constructors and Destructors     ///      /// Initializes a new instance of the  class and installs the keyboard hook.     ///      public globalKeyboardHook()     {         hook();         _disposed = false;     }      public void Dispose()     {         Dispose(true);          // Use SupressFinalize in case a subclass         // of this type implements a finalizer.         GC.SuppressFinalize(this);     }      protected virtual void Dispose(bool disposing)     {         // If you need thread safety, use a lock around these          // operations, as well as in your methods that use the resource.         if (!_disposed)         {             if (disposing)             {                 unhook();             }              // Indicate that the instance has been disposed.             _disposed = true;         }     }      ///      /// Releases unmanaged resources and performs other cleanup operations before the     ///  is reclaimed by garbage collection and uninstalls the keyboard hook.     ///      ~globalKeyboardHook()     {         Dispose();     }     #endregion      #region Public Methods     ///      /// Installs the global hook     ///      public void hook()     {         IntPtr hInstance = LoadLibrary("User32");         hhook = SetWindowsHookEx(WH_KEYBOARD_LL, new keyboardHookProc(hookProc), hInstance, 0);     }      ///      /// Uninstalls the global hook     ///      public void unhook()     {         UnhookWindowsHookEx(hhook);     }      ///      /// The callback for the keyboard hook     ///      /// The hook code, if it isn't >= 0, the function shouldn't do anyting     /// The event type     /// The keyhook event information     ///      public int hookProc(int code, int wParam, ref keyboardHookStruct lParam)     {         if (code >= 0)         {             Keys key = (Keys)lParam.vkCode;             if (HookedKeys.Contains(key))             {                 KeyEventArgs kea = new KeyEventArgs(key);                 if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null))                 {                     KeyDown(this, kea);                 }                 else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null))                 {                     KeyUp(this, kea);                 }                 if (kea.Handled)                     return 1;             }         }         return CallNextHookEx(hhook, code, wParam, ref lParam);     }     #endregion      #region DLL imports     ///      /// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null     ///      /// The id of the event you want to hook     /// The callback.     /// The handle you want to attach the event to, can be null     /// The thread you want to attach the event to, can be null     /// a handle to the desired hook     [DllImport("user32.dll")]     static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);      ///      /// Unhooks the windows hook.     ///      /// The hook handle that was returned from SetWindowsHookEx     /// True if successful, false otherwise     [DllImport("user32.dll")]     static extern bool UnhookWindowsHookEx(IntPtr hInstance);      ///      /// Calls the next hook.     ///      /// The hook id     /// The hook code     /// The wparam.     /// The lparam.     ///      [DllImport("user32.dll")]     static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);      ///      /// Loads the library.     ///      /// Name of the library     /// A handle to the library     [DllImport("kernel32.dll")]     static extern IntPtr LoadLibrary(string lpFileName);     #endregion     } } 

I updated the code with IDisposable. I am probably horribly off on what I am supposed to do but its still not working

回答1:

The problem is that:

hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0); 

is just syntactic sugar for:

hhook = SetWindowsHookEx(WH_KEYBOARD_LL, new keyboardHookProc(hookProc), hInstance, 0); 

and so the keyboardHookProc object is just local and will get disposed of since SetWindowsHookEx doesn't do anything to actually hold onto it in the managed world.

To fix this, up at the top where you define your member variables, add one more like this:

IntPtr hhook = IntPtr.Zero private keyboardHookProc hookProcDelegate; 

then change your constructor to be:

public globalKeyboardHook() {     hookProcDelegate = hookProc;     hook(); } 

and then change your hook() method to be:

public void hook() {     IntPtr hInstance = LoadLibrary("User32");     hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProcDelegate, hInstance, 0); } 

That way you're using a delegate that is stored as a member variable and will be alive as long as your globalKeyboardHook object is alive.



回答2:

Sounds to me like you are instantiating a globalKeyboardHook then letting it get garbage collected. I'm guessing you do something like this:

public void InstallHook() {     var hook = new globalKeyboardHook(); } 

You need to keep a reference to the globalKeyboardHook() around to prevent it from being garbage collected.

globalKeyboardHook hook;  public void InstallHook() {     hook = new globalKeyboardHook(); } 


回答3:

even though with the new code I am still getting the mentioned error, as a solution I just kept an instance of the delegate at class scope, now the error does not come up anymore.

//do not forget to declare kbhproc class var    this.kbhProc = new keyboardHookProc(hookProc); hhook = SetWindowsHookEx(WH_KEYBOARD_LL, this.kbhProc /*new keyboardHookProc(hookProc)*/, hInstance, 0); 

the above code is based on the code of the question.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!