在给Word程序添加hook程序时出现了'System.Runtime.InteropServices.SEHException' 异常,异常详细信息为

'System.Runtime.InteropServices.SEHException' occurred in Unknown Module.
Additional information: External component has thrown an exception.
An exception 'System.NullReferenceException' has occured in...

追踪了很久也找不到问题所在,只是知道异常出现在hook程序中,并切程序一开始并不出现异常,过一段时间之后才会出现异常。
下面是原来的代码:
处理C# hook程序的SEHException异常public void SetUpHookProgram()
{
处理C# hook程序的SEHException异常            HookProc windowCallBack 
= new HookProc(KeyboardProc);
处理C# hook程序的SEHException异常            m_intHookPtr 
= Win32API.SetWindowsHookEx(HookType.WH_KEYBOARD ,windowCallBack,IntPtr.Zero, AppDomain.GetCurrentThreadId());
处理C# hook程序的SEHException异常
处理C# hook程序的SEHException异常            
//If SetWindowsHookEx fails.
处理C# hook程序的SEHException异常
            if(m_intHookPtr == 0 )
{
处理C# hook程序的SEHException异常                Debug.WriteLine(
"SetWindowsHookEx Failed");
处理C# hook程序的SEHException异常                
return;
处理C# hook程序的SEHException异常            }

处理C# hook程序的SEHException异常        }

最后怀疑是垃圾回收器的问题,怀疑他把windowCallback给回收了:
更改代码,把windowCallback作为类成员,在构造函数中初始化

处理C# hook程序的SEHException异常        /// setup hook program to deal with word document
处理C# hook程序的SEHException异常        
/// </summary>
处理C# hook程序的SEHException异常        public void SetUpHookProgram()
{
处理C# hook程序的SEHException异常                       
//m_objHookProc是类的成员,在构造函数中初始化
处理C# hook程序的SEHException异常
            m_intHookPtr = Win32API.SetWindowsHookEx(HookType.WH_KEYBOARD ,m_objHookProc,IntPtr.Zero, AppDomain.GetCurrentThreadId());
处理C# hook程序的SEHException异常
处理C# hook程序的SEHException异常            
//If SetWindowsHookEx fails.
处理C# hook程序的SEHException异常
            if(m_intHookPtr == 0 )
{
处理C# hook程序的SEHException异常                Debug.WriteLine(
"SetWindowsHookEx Failed");
处理C# hook程序的SEHException异常                
return;
处理C# hook程序的SEHException异常            }

处理C# hook程序的SEHException异常        }


问题解决。 
结论:使用Window API时,如果需要传入Delegete作为参数,要自己保证Delegete的生命周期足够长,这种情况下最好声明为类成员,因为如果你声明为局部变量,所在作用域执行结束,Delegete会被回收。

相关文章:

  • 2022-12-23
  • 2021-10-10
  • 2021-07-04
  • 2022-12-23
  • 2022-02-02
  • 2022-02-15
  • 2022-01-02
猜你喜欢
  • 2022-02-20
  • 2022-12-23
  • 2021-09-11
  • 2022-12-23
  • 2021-11-10
  • 2021-05-20
相关资源
相似解决方案