The 'System. runtime. interopservices. sehexception' exception occurred when you added the hook program to the word program. The exception details are as follows:
'System. runtime. interopservices. sehexception' occurred in unknown module.
Additional information: external component has thrown an exception.
An exception 'System. nullreferenceexception' has occured in...
After tracing for a long time, the problem cannot be found, but the exception occurs in the hook program, and the split program does not have an exception at the beginning. After a while, the exception will occur.
The original code is as follows:
Public void setuphookprogram ()
{
Hookproc windowcallback = new hookproc (keyboardproc );
M_inthookptr = WIN32API. setwindowshookex (hooktype. wh_keyboard, windowcallback, intptr. Zero, appdomain. getcurrentthreadid ());
// If setwindowshookex fails.
If (m_inthookptr = 0)
{
Debug. writeline ("setwindowshookex failed ");
Return;
}
}
Finally, I suspect it is a problem with the garbage collector. I suspect that he has recycled windowcallback:
Change the code, use windowcallback as a class member, and initialize it in the constructor.
/** // <Summary>
/// Setup hook program to deal with Word Document
/// </Summary>
Public void setuphookprogram ()
{
// M_objhookproc is a member of the class and is initialized in the constructor.
M_inthookptr = WIN32API. setwindowshookex (hooktype. wh_keyboard, m_objhookproc, intptr. Zero, appdomain. getcurrentthreadid ());
// If setwindowshookex fails.
If (m_inthookptr = 0)
{
Debug. writeline ("setwindowshookex failed ");
Return;
}
}
Solve the problem.
Conclusion: when using the window API, if delegete needs to be input as the parameter, you must ensure that the lifecycle of delegete is long enough. In this case, it is best to declare it as a class member, because if you declare it as a local variable and the execution in the scope ends, delegete will be recycled.