代码之家  ›  专栏  ›  技术社区  ›  Michael Z.

SetWinEventHook每次运行应用程序时只点击一次回调

  •  0
  • Michael Z.  · 技术社区  · 7 年前

    我有一个类,可以在CTRL+ALT+DEL屏幕可见时侦听。当我运行我的应用程序时,它只工作一次,然后再也不会点击回调。有时它似乎会导致内存泄漏,给我一个 System.AccessViolationException

    我做错了什么?为什么它只执行一次回调?

    public static void StartListeningForDesktopSwitch()
    {
        SetWinEventHook(EVENT_SYSTEM_DESKTOPSWITCH, EVENT_SYSTEM_DESKTOPSWITCH,
            IntPtr.Zero, EventCallback, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNTHREAD);
    }
    
    public static void EventCallback(IntPtr hWinEventHook, uint eventType,
        IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        //do stuff when secure desktop is shown or hidden
        Log.LogEvent("Info", "Secure Desktop Event", "", "", null);
    }
    
    public delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType,
        IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
    
    
    [DllImport("user32.dll")]
    static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr
            hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess,
        uint idThread, uint dwFlags);
    
    const uint WINEVENT_OUTOFCONTEXT = 0x0000;
    const uint WINEVENT_SKIPOWNTHREAD = 0x0001;
    const uint EVENT_SYSTEM_DESKTOPSWITCH = 0x0020;
    

    WindowEventHook.StartListeningForDesktopSwitch();

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ilian    7 年前

    你是如何使用外部变量的?

    public static class WindowEventHook
    {
        private static readonly WinEventDelegate callback = EventCallback;
    
        public static void StartListeningForDesktopSwitch()
        {
            SetWinEventHook(EVENT_SYSTEM_DESKTOPSWITCH, EVENT_SYSTEM_DESKTOPSWITCH,
                IntPtr.Zero, callback, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNTHREAD);
        }
    
        ...
    }