在BHO(浏览器帮助程序对象)中使用时,SetWinEventHook使IE崩溃。 [英] SetWinEventHook crahes IE when used in BHO (Browser Helper Object)

查看:181
本文介绍了在BHO(浏览器帮助程序对象)中使用时,SetWinEventHook使IE崩溃。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#BHO,它设置了一个挂钩,以便我可以跟踪IE何时获得焦点:

I have a C# BHO which sets a hook so that I can track when IE gets focus:

public class BHO : IObjectWithSite, IOleCommandTarget
{
    delegate void WinEventDelegate(IntPtr hWinEventHook,
       uint eventType, IntPtr hwnd, int idObject,
       int idChild, uint dwEventThread, uint dwmsEventTime);

    const uint WINEVENT_OUTOFCONTEXT = 0;
    const uint EVENT_SYSTEM_FOREGROUND = 3;

    [DllImport("user32.dll")]
    static extern bool UnhookWinEvent(IntPtr hWinEventHook);
    [DllImport("user32.dll")]
    static extern IntPtr SetWinEventHook(uint eventMin,
        uint eventMax, IntPtr hmodWinEventProc,
        WinEventDelegate lpfnWinEventProc, uint idProcess,
        uint idThread, uint dwFlags);

   private static IntPtr m_hhook; 


       ............

        m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND,
           EVENT_SYSTEM_FOREGROUND, IntPtr.Zero,
           WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT);



       ............


   void WinEventProc(IntPtr hWinEventHook, uint eventType,
             IntPtr hwnd, int idObject, int idChild,
             uint dwEventThread, uint dwmsEventTime)
    {

    }

它工作了一段时间,然后IE崩溃,并显示尝试读取或写入受保护的内存。这通常表明其他内存已损坏。

It works for a while and then IE crashes with "Attempted to read or write protected memory. This is often an indication that other memory is corrupt"

请注意,即使WinEventProc中没有任何内容,它也会崩溃(如上所示)。如果我不设置钩子,它将永远不会崩溃。

Note that it crashes even when there is nothing in WinEventProc (as shown above). If I don't set the hook, it never crashes.

有什么想法吗?

推荐答案

您的回调委托可能正在获取GC。代替使用自动创建委托的功能,创建一个显式的委托,将其传递给SetWinEventHook,然后将其保留在实例成员中,直到完成为止。

Your callback delegate might be getting GC'd. Instead of using the automatic delegate creation feature, create an explicit one, pass that to SetWinEventHook, and then keep it around in an instance member until you're done with it.

代码可能类似于:

// In the class...
WinEventDelegate m_wineventprocDelegate;


// When you register the hook...
m_wineventprocDelegate = new winEventDelegate(WinEventProc);

// Pass in the delegate instead of WinEventProc
m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND,
       EVENT_SYSTEM_FOREGROUND, IntPtr.Zero,
       m_wineventprocDelegate, 0, 0, WINEVENT_OUTOFCONTEXT);

拥有成员引用的代表可防止其被收集。

Having the delegate referenced by a member keeps it from getting collected.

这篇关于在BHO(浏览器帮助程序对象)中使用时,SetWinEventHook使IE崩溃。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆